Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

io

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?

like image 468
PhoonOne Avatar asked Mar 24 '13 17:03

PhoonOne


People also ask

Does \n count as a single character?

The newline character is a single (typically 8-bit) character. It's represented in program source (either in a character literal or in a string literal) by the two-character sequence \n . So '\n' is a character constant representing a single character, the newline character.

Is New line two characters?

You need to advance to the next line on the page AND return to the beginning of the line, hence CRLF , two characters.

Is newline considered a character?

LF (character : \n, Unicode : U+000A, ASCII : 10, hex : 0x0a): This is simply the '\n' character which we all know from our early programming days. This character is commonly known as the 'Line Feed' or 'Newline Character'.

How many characters is a newline?

In most file formats, no line terminators are actually stored. Operating systems for the CDC 6000 series defined a newline as two or more zero-valued six-bit characters at the end of a 60-bit word.


1 Answers

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.

like image 83
Martijn Pieters Avatar answered Oct 02 '22 10:10

Martijn Pieters