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

david.stegbauer at cz.opel.com david.stegbauer at cz.opel.com
Tue May 18 10:02:09 EDT 1999


Oliver Steele <steele at cs.brandeis.edu> write:
>
> regardless of file modes, f.seek(f.tell()) should be a noop
>
> Not so. On a Windows machine 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.
>
>     f = open('test.txt', 'wb')
[snip]
> NT>>> testseek()
> 'a\012'
> '\012'
>
> UNIX>>> testseek()
> 'b\012'
> 'b\012'
>
> MacOS>>> testseek()
> ''
> ''

You HAVE TO read file consistently: if created in binary mode has to be read in
binary mode. If created in text mode, has to be read in text mode. On unix and
mac are both the same not in M$.

M$ DOS and its successors stores new line as 0x0d 0x0a in text mode and only as
0x0a in binary mode. Text mode is default. So with f = open('test.txt', 'wb');
f.write('a\nb\n'); f.close() you will create 4-bytes file only (hex "61 0A 62
0A") instead of 6-bytes.

So open(..., 'wb')  -->  open(..., 'rb')
   open(..., 'wt')  -->  open(..., 'rt')



def testseek():
    # create a two-line file
    f = open('d:\\test.txt', 'wb')
    f.write('a\nb\n')
    f.close()
    # read it
    f = open('d:\\test.txt', 'r')
    print "\nline A"
    f.seek(0); print `f.readline()`; print `f.tell()`
    print `f.readline()`; print `f.tell()`
    print "\nline B"
    f.seek(0); print `f.readline()`; print `f.tell()`;
    f.seek(f.tell()); print `f.tell()`;
    print `f.readline()`;print `f.tell()`
    f.close()

>>> testseek()

line A
'a\012'
1
'b\012'
4

line B
'a\012'
1
1
'\012'
1

now, if I replace 'wb' mode with 'w' (for creating file) I'll get:
>>> testseek()

line A
'a\012'
3
'b\012'
6

line B
'a\012'
3
3
'b\012'
6






More information about the Python-list mailing list