Borislav Hadzhiev
Last updated: Apr 25, 2022
Check out my new book
The Python "ValueError: must have exactly one of create/read/write/append
mode" occurs when we specify an incorrect mode when opening a file. To solve the
error, use the r+
mode if you need to open the file for both reading and
writing.
Here is an example of how the error occurs.
# 👇️ using incorrect 'rw' mode # ⛔️ ValueError: must have exactly one of create/read/write/append mode with open('example.txt', 'rw', encoding='utf-8') as my_file: read_data = my_file.read() print(read_data) my_file.write('first line' + '\n') my_file.write('second line' + '\n') my_file.write('third line' + '\n') my_file.seek(0) print(my_file.read())
We used an unsupported rw
mode which caused the error.
If you need to open a file for both reading and writing, use the r+
mode
instead.
# ✅ using r+ mode with open('example.txt', 'r+', encoding='utf-8') as my_file: read_data = my_file.read() print(read_data) my_file.write('first line' + '\n') my_file.write('second line' + '\n') my_file.write('third line' + '\n') my_file.seek(0) print(my_file.read())
The r+
mode opens the file for reading and writing and positions the stream at
the beginning of the file.
w+
mode being used. It opens the file for reading and writing and creates the file if it doesn't already exist.If the file exists, it is truncated. Truncating the file means that all contents of the file are erased.
with open('example-2.txt', 'w+', encoding='utf-8') as my_file: read_data = my_file.read() print(read_data) my_file.write('first line' + '\n') my_file.write('second line' + '\n') my_file.write('third line' + '\n') my_file.seek(0) print(my_file.read())
On the other hand, the r+
mode doesn't create the file if it doesn't exist,
nor does it truncate the file.
r+
and w+
modes position the stream at the beginning of the file.There is also an a+
mode which opens the file for reading and writing.
The a+
mode creates the file if it doesn't already exist, but it positions the
stream at the end of the file.
with open('example-3.txt', 'a+', encoding='utf-8') as my_file: read_data = my_file.read() print(read_data) my_file.write('first line' + '\n') my_file.write('second line' + '\n') my_file.write('third line' + '\n') my_file.seek(0) print(my_file.read())
The difference between the a+
mode and the other 2 is that the stream is
positioned at the end of the file.
The a+
mode also doesn't truncate the file if it already exists.
You can view all of the other possible modes to open a file in in this table of the official docs.