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

Since Python 3.3, exclusive creation lets you avoid truncating or overwriting an existing file.

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

Open for exclusive creation and handle an existing file:

try:
    with open("fname", "x") as fout:
        # Work with your open file
except FileExistsError:
    # Your error handling goes here
import os.path
if os.path.isfile(fname):
    with open("fname", "w") as fout:
        # 'w' erases the existing file before writing
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