truncating a file from the top down

R

rbt

Hi guys,

I need to truncate a file from the top down. I imagine doing something
like this:

if os.stat says the file is too big:
read the file
trim = only keep the last 2008 bytes (This is where I get stuck)
write trim back out to the original file

Would someone demonstrate the *best* most efficient way of doing this?

Thanks,
rbt
 
M

Mike Rovner

rbt said:
if os.stat says the file is too big:
read the file
trim = only keep the last 2008 bytes (This is where I get stuck)
write trim back out to the original file

Would someone demonstrate the *best* most efficient way of doing this?

if os.stat says the_file is too big:
fh = open(the_file, 'rb')
fh.seek(2008, 2)
data = fh.read()
fh.close()
assert len(data)==2008 # you may want some error processing here
fh = open(the_file, 'wb')
fh.write(data)
fh.close()

/m
 
F

Fredrik Lundh

Mike said:
if os.stat says the_file is too big:
fh = open(the_file, 'rb')
fh.seek(2008, 2)

should be

fh.seek(-2008, 2)

right?
data = fh.read()
fh.close()
assert len(data)==2008 # you may want some error processing here
fh = open(the_file, 'wb')
fh.write(data)
fh.close()

or

if os.path.getsize(the_file) > TOO_BIG:
fh = open(the_file, 'rb+')
fh.seek(-2008, 2)
data = fh.read()
fh.seek(0) # rewind
fh.write(data)
fh.truncate()
fh.close()

</F>
 
M

Mike Rovner

Right. Thanks for the correction.

Fredrik said:
Mike Rovner wrote:




should be

fh.seek(-2008, 2)

right?




or

if os.path.getsize(the_file) > TOO_BIG:
fh = open(the_file, 'rb+')
fh.seek(-2008, 2)
data = fh.read()
fh.seek(0) # rewind
fh.write(data)
fh.truncate()
fh.close()

</F>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,046
Latest member
Gavizuho

Latest Threads

Top