pythonio

is the newline "\n" 2 characters or 1 character


So i have a file.txt:

>>012345
>> (new line)

when I call:

b=a.read(7)
print b

this will give me

 012345
 (with a newline here)

So I see that it has read the next 7 characters, counting the "\n" as a single character. But when I use seek, it seems that it treats "\n" as two characters:

position = a.seek(-2,2)
b=a.read(1)
print b

this prints a new blank line instead of 5.

Do these 2 methods treat "\n" differently?


Solution

  • Python opens files in text mode by default. Files open in text mode have platform-native newline conventions translated to \n automatically.

    You opened a file using the \r\n newline convention, on Windows most probably.

    Open the file in binary mode if you do not want this translation to take place. See the documentation of the open() function for more details:

    The default is to use text mode, which may convert '\n' characters to a platform-specific representation on writing and back on reading. Thus, when opening a binary file, you should append 'b' to the mode value to open the file in binary mode, which will improve portability.