File modes

suggest change

There are different modes you can open a file with, specified by the mode parameter. These include:

with open(filename, 'r') as f:
    f.read()
with open(filename, 'w') as f:
    f.write(filedata)
with open(filename, 'a') as f:
    f.write('\n' + newdata)
What r r+ w w+ a a+
Read ✔ ✔ ✘ ✔ ✘ ✔
Write ✘ ✔ ✔ ✔ ✔ ✔
Creates file ✘ ✘ ✔ ✔ ✔ ✔
Erases file ✘ ✘ ✔ ✔ ✘ ✘
Initial position start start start start end end

Python 3 added a new mode for exclusive creation so that you will not accidentally truncate or overwrite and existing file.

What x x+
Read ✘ ✔
Write ✔ ✔
Creates file ✔ ✔
Erases file ✘ ✘
Initial position start start

Allow one to write your file open code in a more pythonic manner:

try:
    with open("fname", "r") as fout:
        # Work with your open file
except FileExistsError:
    # Your error handling goes here

In Python 2 you would have done something like

import os.path
if os.path.isfile(fname):
    with open("fname", "w") as fout:
        # Work with your open file
else:
    # Your error handling goes here

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents