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 -- http://mail.python.org/mailman/listinfo/python-list