[Tutor] Moving file pointer
gustabares at verizon.net
Thu Jul 29 20:56:43 CEST 2004
This is exactly what I was looking for...thank you.
From: Tim Peters [mailto:tim.peters at gmail.com]
Sent: Thursday, July 29, 2004 2:52 PM
To: Gus Tabares
Cc: tutor at python.org
Subject: Re: [Tutor] Moving file pointer
> I'm trying to set the file pointer for a file on a posix machine. For
> instance, I have a simple 5-byte file with data 'abcde'. I want to
> 'extend' the file to 10-bytes, but not initialize any data in those
> extra 5-bytes. They should be all zeros.
> This is analogous to win32file.SetFilePointer routine.
> Does anyone have any pointers (no pun intended) to a solution?
Portable across POSIX and WinNT/2K/XP:
>>> f = open('blah', 'r+b')
>>> import os
>>> print os.path.getsize('blah')
>>> f.seek(10) # seek to whatever position you want
>>> f.truncate() # force the file size to match
>>> print os.path.getsize('blah') # now it's 10 bytes
>>> open('blah', 'rb').read() # and 5 NULs were appended
This will also change the file length on Win95/98/SE, but on those
there's no predicting what the additional bytes will contain -- they're
whatever bytes happened to be sitting on the disk at those positions.
Seeking beyond the end of the file alone is not enough to change the
file size. You need to "do something" after that. f.truncate() is one
way, or you could simply starting writing to the file then.
More information about the Tutor