File modes
suggest changeThere are different modes you can open a file with, specified by the mode parameter. These include:
'r'- reading mode. The default. It allows you only to read the file, not to modify it. When using this mode the file must exist.'w'- writing mode. It will create a new file if it does not exist, otherwise will erase the file and allow you to write to it.'a'- append mode. It will write data to the end of the file. It does not erase the file, and it creates the file if it does not exist.'rb'- reading mode in binary. This is similar torexcept that the reading is forced in binary mode. It is not the default; the default is'r'.'r+'- reading mode plus writing mode at the same time. This allows you to read and write into files at the same time without having to userandw.'rb+'- reading and writing mode in binary. The same asr+except the data is in binary'wb'- writing mode in binary. The same aswexcept the data is in binary.'w+'- writing and reading mode. Liker+, it allows reading and writing, but it creates the file if needed and truncates an existing file.'wb+'- writing and reading mode in binary mode. The same asw+but the data is in binary.'ab'- appending in binary mode. Similar toaexcept that the data is in binary.'a+'- appending and reading mode. It creates the file if it does not exist and does not truncate an existing file. The initial position is the end of the file.'ab+'- appending and reading mode in binary. The same asa+except that the data is in binary.
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.
'x'- open for exclusive creation, will raiseFileExistsErrorif the file already exists'xb'- open for exclusive creation writing mode in binary. The same asxexcept the data is in binary.'x+'- reading and writing mode. It creates a new file and raisesFileExistsErrorif the file already exists.'xb+'- writing and reading mode. The exact same asx+but the data is binary
| 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
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents