interaction of mode 'r+', file.write(), and file.tell(): a bug or undefined behavior?

Lie Ryan lie.1296 at gmail.com
Thu Jan 28 07:12:22 EST 2010


In the code:

"""
f = open('input.txt', 'r+')
for line in f:
    s = line.replace('python', 'PYTHON')
    # f.tell()
    f.write(s)
"""

When f.tell() is commented, 'input.txt' does not change; but when
uncommented, the f.write() succeeded writing into the 'input.txt'
(surprisingly, but not entirely unexpected, at the end of the file).


$ #####################################
$
$ cp orig.txt input.txt
$ cat input.txt
abcde
abc python abc
python abc python
$ python
Python 2.6.4 (r264:75706, Jan 12 2010, 05:24:27)
[GCC 4.3.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> f = open('input.txt', 'r+')
>>> for line in f:
...     s = line.replace('python', 'PYTHON')
...     f.write(s)
...
>>>
$ cat input.txt
abcde
abc python abc
python abc python
$
$ #####################################
$
$ cp orig.txt input.txt
$ cat input.txt
abcde
abc python abc
python abc python
$ python
Python 2.6.4 (r264:75706, Jan 12 2010, 05:24:27)
[GCC 4.3.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> f = open('input.txt', 'r+')
>>> for line in f:
...     s = line.replace('python', 'PYTHON')
...     f.tell()
...     f.write(s)
...
39
45
60
>>>
$ cat input.txt
abcde
abc python abc
python abc python
abcde
abc PYTHON abc
$
$ #####################################



Do you think this should be a bug or undefined behavior governed by the
underlying OS and C library? Shouldn't file.tell() be purely
informational, and not have side effect?




The machine is Gentoo (amd64, gcc-4.3.4, glibc-2.10.1-r1), Linux
(2.6.31-gentoo-r6), and Python 2.6.4



More information about the Python-list mailing list