reading and removing first x bytes of a file

Peter Hansen peter at engcorp.com
Thu Apr 29 11:47:50 EDT 2004


bart_nessux wrote:

> Thanks Peter, the below code recursively read the first 128B... am I 
> right in saying that? 

Well, your indentation is screwed up, for one thing, so I can't
guarantee the code does what you want.  I'll leave actually testing
it up to you...

> If so, now that I can read these bytes from all 
> .bin files in a directory, what would be the safest and fastest way of 
> removing them?

Define 'safe' and describe how fast you want it to run. <wink>

Anyway, you can't actually "remove" bytes from the files, so
what you really need to do is then read the *rest* of the bytes
(i.e. keep the file open after the first read, and do a .read()
of the rest of the data) and then write the shortened data to
a temporary file (module tempfile can be helpful here), then
once that's worked, use os.remove to remove the old file, and
os.rename to rename the temp file to the same name as the old
file.

-Peter



More information about the Python-list mailing list