>012345 >> (new line) when i call: b=a.read(7) print b it will give me ...">

This is a newline \ n "2 or 1 character

So I have a .txt file:

>>012345 >> (new line) 

when i call:

 b=a.read(7) print b 

it will give me

  012345 (with a newline here) 

So, I see that he read the next 7 characters, counting "\ n" as one character. But when I use seek, it seems like 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 handle " \n " differently?

+7
source share
2 answers

Python opens files in text mode by default. Files opened in text mode have platform-compatible newline rules translated to \n automatically.

You opened the file using the \r\n newline convention on Windows most likely.

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

By default, text mode is used, which can convert the characters '\n' to a platform-specific representation when writing and reading. Thus, when opening a binary file, you must add 'b' to the mode value to open the file in binary mode, which will improve portability.

+9
source

You do not need to do this yourself. Python comes with batteries included. :-)

If new lines bother you, just read() entire file and use the splitlines() method for lines;

 In [21]: test = 'foo \nbar bla\n baz\r\n' In [22]: test.splitlines() Out[22]: ['foo ', 'bar bla', ' baz'] 

Note that this only removes spaces at the end of lines.

0
source

All Articles