Bug? On WindowsNT, f.seek() and f.tell() aren't symmetric

Oliver Steele steele at cs.brandeis.edu
Tue May 18 07:10:41 EDT 1999


My reading of the Python Library documentation
<http://www.python.org/doc/lib/bltin-file-objects.html> is that,
regardless of file modes, f.seek(f.tell()) should be a noop (assuming f
is bound to an open file):
  f.seek(0); f.readline(); print `f.readline()`
and
  f.seek(0); f.readline(); f.seek(f.tell()); print `f.readline()`
should print the same value.

Not so. On a Windows machine (specifically, an SGI running WindowsNT and
Python 1.5.2 final), the function below prints 'a\012' for the first
line and '\012' for the second.  Changing the file open mode to 'rb' or
running the program on a Mac or UNIX machine works fine.

Note that it's not the fact that different platforms yield different results
that's an issue -- that's expected, given the platform-dependent file that
the write() statement creates.  It's the fact that that there's any platform
such that the two lines below labeled 'line A' and 'line B' yield different
results on the platform, that disagrees with my understanding of the Python
documentation.

The upshot of this is that it's possible to develop a Python program under
MacOS or UNIX, using the documentation available on those platforms, that
fails under NT -- in other words, it demotes Python to the status of a
'write once test everywhere language'.  I ran across this in code I
developed on the Mac as an interface to the WordNet lexical database; the
fix was to open the local files in 'rb' mode on Windows, and 'r' mode
elsewhere.

def testseek():
    # create a two-line file
    f = open('test.txt', 'wb')
    f.write('a\nb\n')
    f.close()

    # read it
    f = open('test.txt', 'r')
    f.seek(0); f.readline(); print `f.readline()` # line A
    f.seek(0); f.readline(); f.seek(f.tell()); print `f.readline()` # line B
    f.close()

NT>>> testseek()
'a\012'
'\012'

UNIX>>> testseek()
'b\012'
'b\012'

MacOS>>> testseek()
''
''




More information about the Python-list mailing list