how to remove n bytes in a file?
Tim Chase
python.list at tim.thechases.com
Sat Sep 2 11:21:11 EDT 2006
> def shift(f, offset, size, buffer_size=1024*1024):
Slight bug in that function implementation. This one passes my
tests.
Sorry about that.
-tkc
def shift(f, offset, size, buffer_size=1024*1024):
"""deletes (in place) a portion of size "size" from file "f",
starting at offset "offset"
The buffer_size can be tweaked for system preferences,
defaulting to 1 megabyte.
"""
f.seek(offset + size)
while True:
buffer = f.read(buffer_size)
if not buffer: break
f.seek(offset)
f.write(buffer)
offset += buffer_size
f.seek(offset + size)
f.seek(-size,2)
f.truncate()
if __name__ == '__main__':
offset = ord('p')
size = 5
buffer_size = 10
from StringIO import StringIO
s = ''.join([chr(i) for i in xrange(256)])
print repr(s)
print "="*50
f = StringIO(s)
# delete "p" through "u"
shift(f, offset, size, buffer_size)
f.seek(0)
result = f.read()
print repr(result)
More information about the Python-list
mailing list