Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between parsing a text file in r and rb mode

What makes parsing a text file in 'r' mode more convenient than parsing it in 'rb' mode? Especially when the text file in question may contain non-ASCII characters.

like image 352
MxLDevs Avatar asked Mar 10 '12 05:03

MxLDevs


People also ask

What is difference between R and RB mode?

r : Opens the file in read-only mode. Starts reading from the beginning of the file and is the default mode for the open() function. rb : Opens the file as read-only in binary format and starts reading from the beginning of the file.

Can text files be opened in RB mode?

The open() function opens a file in text format by default. To open a file in binary format, add 'b' to the mode parameter. Hence the "rb" mode opens the file in binary format for reading, while the "wb" mode opens the file in binary format for writing. Unlike text files, binary files are not human-readable.

What is the meaning of R b in binary mode?

r+ is used for reading, and writing mode. b is for binary. r+b mode is open the binary file in read or write mode.


1 Answers

This depends a little bit on what version of Python you're using. In Python 2, Chris Drappier's answer applies.

In Python 3, its a different (and more consistent) story: in text mode ('r'), Python will parse the file according to the text encoding you give it (or, if you don't give one, a platform-dependent default), and read() will give you a str. In binary ('rb') mode, Python does not assume that the file contains things that can reasonably be parsed as characters, and read() gives you a bytes object.

Also, in Python 3, the universal newlines (the translating between '\n' and platform-specific newline conventions so you don't have to care about them) is available for text-mode files on any platform, not just Windows.

like image 196
lvc Avatar answered Sep 28 '22 10:09

lvc