I have created a text fine named nameFile.txt
. It has the following text.
This is a file.
It will be read from program.
When I'm opening a file in normal mode it showing me the text from "nameFile.txt".
nameFile = open("nameFile.txt")
fromFile = nameFile.read()
print(fromFile)
nameFile.close()
Output:
This is a file.
It will be read from program.
When I'm opening a file in binary mode it's showing something like this:
nameFile = open("nameFile.txt", "rb")
Output:
b'This is a file.\r\nIt will be read from program.'
Why my output is including some extra escape sequences like b, \r, \n?
In text mode what matters is... text. There are "normal" characters (letters, numbers, punctuation and so on) and there are special characters. Many of the latter, for example the new line char (\n
), the carriage return (\r
) and the tabulation (\t
) have a specific role in affecting the presentation of the text.
That's why in text mode \r\n
is shown as a new line, and not explicitly.
In binary mode is different: all characters are supposed to be just bytes, not something to be interpreted to better present a text. And that's why all the characters are shown when it comes to print the content of a file open in binary mode.
Note: the b
shown at the beginning, just before the actual file, just means "here it is a file presented in binary mode".