Lesson 02
File Opening Modes — r, w, a, r+, w+, a+, x, and x+
Learn each of the eight Python file modes — r, w, a, r+, w+, a+, x, and x+ — including overwrite, append, and exclusive create.
The mode tells Python whether you may read, write, append, or create the file, and what happens if that name already exists.
Use the playground at the bottom of this page, then take the quiz.
What you will learn
- The eight opening modes:
r,w,a,r+,w+,a+,x,x+ - Which modes create a file and which modes require it to exist
- The difference between overwrite, append, and exclusive create
- Which exception appears when the mode and the file do not match
The idea
If you omit the mode, Python uses "r". Read modes fail with FileNotFoundError when the name is missing. The exception for an exclusive create that finds an existing file is FileExistsError.
| Mode | File must exist? | Read | Write | If the file already exists |
|---|---|---|---|---|
r |
Yes | Yes | No | Leave it unchanged |
w |
No | No | Yes | Overwrite the old data |
a |
No | No | Yes | Append after the old data |
r+ |
Yes | Yes | Yes | Keep data; pointer starts at the beginning |
w+ |
No | Yes | Yes | Overwrite, then you may read |
a+ |
No | Yes | Yes | Append; seek to the start before reading |
x |
No | No | Yes | FileExistsError if the name exists |
x+ |
No | Yes | Yes | FileExistsError if the name exists |
w and w+ are for a fresh copy of the file. a and a+ keep what is already there and add more. x and x+ create the name once. Use them when accidentally replacing a file would be a mistake.
After a w+ write, the pointer sits at the end. Call seek(0) before read() if you want the text you just stored. The same seek is required for a+.
Example
with open("notebook.txt", "w", encoding="utf-8") as handle:
handle.write("Avery Lane\n")
with open("notebook.txt", "a", encoding="utf-8") as handle:
handle.write("Jordan Hale\n")
with open("notebook.txt", "r", encoding="utf-8") as handle:
print(handle.read())The first write creates the file. The second open uses append, so the first line is still there. Change "a" to "w" in the playground and run again: the first line disappears because write mode overwrites.
Key takeaways
-
"r"is the default and raisesFileNotFoundErrorif the file is missing -
"w"overwrites;"a"appends -
+adds the other direction: read and write -
"x"creates a file only when the name is new -
The real exception name is
FileExistsError -
Previous: Files and Streams
-
Next: open() and with open()
Loading playground…
Check your understanding
File opening modes quiz
The default file mode is:
1 / 10