[Tutor] Moving file pointer

Tim Peters tim.peters at gmail.com
Thu Jul 29 20:51:48 CEST 2004

[Gus Tabares]
> 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
>>> f.close()
>>> 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

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 mailing list