Open files in "rt" and "wt" modes

Several times here on SO, I saw people using rt and wt modes to read and write files.

For example:

 with open('input.txt', 'rt') as input_file: with open('output.txt', 'wt') as output_file: ... 

I do not see the modes documented , but since open() does not throw an error - it seems that it is quite legal to use.

What is it and is there a difference between using wt vs w and rt vs r ?

+53
python file file-io
Apr 14 '14 at 2:33
source share
4 answers

t refers to text mode. There is no difference between r and rt or w and wt , since text mode is the default.

Documented here :

 Character Meaning 'r' open for reading (default) 'w' open for writing, truncating the file first 'x' open for exclusive creation, failing if the file already exists 'a' open for writing, appending to the end of the file if it exists 'b' binary mode 't' text mode (default) '+' open a disk file for updating (reading and writing) 'U' universal newlines mode (deprecated) 
+98
Apr 14 '14 at 2:36 on
source share

t indicates text mode, which means that the \n characters will be translated to the end of the line of the host operating system when writing to the file and vice versa when reading. The flag is basically just noise, since text mode is the default.

In addition to U , these mode flags come directly from the standard fopen() function of the C library, which is recorded in the sixth paragraph of the python2 documentation for open() .

As far as I know, t not and has never been part of the C standard, therefore, although many implementations of the C library accept it anyway, there is no guarantee that they will all be, and therefore, do not guarantee that this will work on each python build This explains why the python2 docs did not list it and why it generally worked anyway. python3 docs make it official.

+7
Nov 08 '14 at 5:15
source share

"r" is for reading, "w" is for writing, and "a" is for adding.

"t" is a text mode that is used in binary mode.

Several times here on SO, I saw people using rt and wt modes to read and write files.

Edit: Are you sure you saw rt, not rb?

These functions usually wrap the fopen function, which is described here:

http://www.cplusplus.com/reference/cstdio/fopen/

As you can see, it mentions using b to open a file in binary mode.

The referenced document link also refers to this mode b:

Adding "b" is useful even on systems that do not process binary and text files differently, where they serve in the documentation.

+4
Apr 14 '14 at 2:36 on
source share

t indicates text mode

https://docs.python.org/release/3.1.5/library/functions.html#open

on linux there is no difference between text mode and binary mode, however in windows they convert \n to \r\n in text mode.

http://www.cygwin.com/cygwin-ug-net/using-textbinary.html

+3
Apr 14 '14 at 2:38
source share



All Articles