Show the effect of the Python file modes r, w, a and x.
The four modes differ in what they do to a file that already exists.
# w creates the file, or empties it when it is already there.
with open('modes.txt', 'w', encoding='utf-8') as handle:
handle.write('one\n')
# a creates the file, or adds to the end of it.
with open('modes.txt', 'a', encoding='utf-8') as handle:
handle.write('two\n')
# r only reads the file.
with open('modes.txt', 'r', encoding='utf-8') as handle:
print(handle.read().split())
# x creates the file only when it is not already there.
try:
open('modes.txt', 'x', encoding='utf-8').close()
except FileExistsError as error:
print('FileExistsError:', error)
The output is the list ['one', 'two'] followed by the FileExistsError. The w mode created the file and wrote one line, the a mode added a second line without erasing the first, and the r mode read both of them back. The x mode refused to open a file that already existed.
The summary is short. The r mode reads, the w mode writes and empties the file, the a mode adds to the end, and the x mode creates the file only if it is not there yet. Three of them create the file when it is missing, and only r insists that it already exists. The emptying behaviour of w is the one that surprises people, because opening a file in w mode and then failing before you write anything leaves you with an empty file. A safer pattern is to write to a temporary file and then rename it into place.