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?
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.
You need to advance to the next line on the page AND return to the beginning of the line, hence CRLF , two characters.
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'.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With