I find it important to note that python 3 defines the opening modes differently to the answers here that were correct for Python 2.
The Python 3 opening modes are:
'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 (for backwards compatibility; should not be used in new code)
The modes r
, w
, x
, a
are combined with the mode modifiers b
or t
. +
is optionally added, U
should be avoided.
As I found out the hard way, it is a good idea to always specify t
when opening a file in text mode since r
is an alias for rt
in the standard open()
function but an alias for rb
in the open()
functions of all compression modules (when e.g. reading a *.bz2
file).
Thus the modes for opening a file should be:
rt
/ wt
/ xt
/ at
for reading / writing / creating / appending to a file in text mode and
rb
/ wb
/ xb
/ ab
for reading / writing / creating / appending to a file in binary mode.
Use +
as before.