Python tell() behaving differently regarding position in the current file
In the book - Core Python Programming, there is following example -
>>> f = open('/tmp/x', 'w+') >>> f.tell() 0 >>> f.write('test line 1\n') # add 12-char string [0-11] >>> f.tell() 12 >>> f.write('test line 2\n') # add 12-char string [12-23] >>> f.tell() # tell us current file location (end)) 24
When I run the same code in my interpreter, I get 13L in place of 12 and 26L in place of 24. I am running python 2.5 on Windows开发者_如何学运维.
Has anything changed regarding behaviour or tell() in versions? How does tell decide the position in the file.
Thanks and Regards
Your file is opened in text mode. In that mode Python on Windows makes a translation between Windows line-endings and Unix line endings. On Windows a line ending is two characters while on Unix it is one ('\n'
), hence your result is expected.
If you open the file in binary mode, you don't get these translations.
f = open('/tmp/x', 'wb+')
And you would get 12 and 24 back from tell()
as well.
It's because newlines in Windows are two characters, CR and LF. On Unix they are just one, LF. By default, Python will convert \n
to be your OS's notion of a newline.
The L
you are seeing simply tells you that the number is a long integer.
>>> f = open('c:\\temp\\foo', 'w+')
>>> f.tell()
0L
>>> f.write('test line 1\n')
>>> f.tell()
13L
>>> g = open('c:\\temp\\bar', 'wb+')
>>> g.tell()
0L
>>> g.write('test line 1\n')
>>> g.tell()
12L
>>>
That is because of newlines. :) On Unix is it '\n' and Mac '\r' and most probably the author of core-python was using this. You are on Windows and it is '\r\n' and so you are getting additional character counted.
精彩评论