Python — File Write Modes


As a newbie, I often couldn’t find information on file write modes, like rb, U, etc. 

Python has great documentation…. open a python interpreter, type help(file) and you will see:

class file(object)

file(name[, mode[, buffering]]) -> file object

Open a file.  The mode can be ‘r’, ‘w’ or ‘a’ for reading (default),

writing or appending.  The file will be created if it doesn’t exist

when opened for writing or appending; it will be truncated when

opened for writing.  Add a ‘b’ to the mode for binary files.

Add a ‘+’ to the mode to allow simultaneous reading and writing.

If the buffering argument is given, 0 means unbuffered, 1 means line

buffered, and larger numbers specify the buffer size.

Add a ‘U’ to mode to open the file for input with universal newline

support.  Any line ending in the input file will be seen as a ‘\n’

in Python.  Also, a file so opened gains the attribute ‘newlines’;

the value for this attribute is one of None (no newline read yet),

  ‘\r’, ‘\n’, ‘\r\n’ or a tuple containing all the newline types seen.

‘U’ cannot be combined with ‘w’ or ‘+’ mode.


Mmmm. Perfect. One of the reason why I like Django so much is the documentation. Freaking amazing! So many python questions have been self answered by just typing help( blah ). 



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s