By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
439,932 Members | 1,944 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 439,932 IT Pros & Developers. It's quick & easy.

truncating a file from the top down

P: n/a
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
Jul 18 '05 #1
Share this Question
Share on Google+
4 Replies


P: n/a
rbt wrote:
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

Jul 18 '05 #2

P: n/a
Mike Rovner wrote:
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>

Jul 18 '05 #3

P: n/a
Right. Thanks for the correction.

Fredrik Lundh wrote:
Mike Rovner wrote:

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>


Jul 18 '05 #4

P: n/a
rbt
Mike Rovner wrote:
Right. Thanks for the correction.

Fredrik Lundh wrote:
Mike Rovner wrote:

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>


Thanks for the info guys!
Jul 18 '05 #5

This discussion thread is closed

Replies have been disabled for this discussion.