How to Solve Python ValueError: must have exactly one of create/read/write/append mode

by | Programming, Python, Tips

This error occurs when you pass an incorrect mode to an open() function call. If you want to open a file for both reading and writing you can use r+ only if the file exists. You can use w+ if the file does not exist or if you do not mind overriding an existing file. You can also use a+ if the file does not exist or if you want to add to an existing file.

For example,

with open('celeb_names.txt', 'r+') as f:

    lines = f.readlines()

    for line in lines:

        print(line)

    f.write('Pam Grier'+'\n')

This tutorial will go through the error in detail and how to solve it with code example.


Python ValueError: must have exactly one of create/read/write/append mode

In Python, a value is the information stored within a particular object. We will encounter a ValueError in Python when we use an operation or function that receives an argument with the right type but an inappropriate value.

The open function has several modes:

  • r‘ : Read – Default value. Opens a file to read, raises an error if the file does not exist
  • a‘ : Append – Opens a file to append, creates the file if it does not exist
  • w‘ : Write – Opens a file to write, creates the file if it does not exist
  • x‘ : Create – Creates the specified file, returns an error if it does not exist

And we can specify how to handle the file by adding either of the two following characters after the create/read/write/append mode:

  • t‘ : Text – Default value. Text mode.
  • b‘ : Binary – Binary mode

The open() function can only have one specified mode with the additional binary/text mode if specified. For example, ‘rb‘ for open the file to read in binary mode.

If you specify more than one of the create/read/write/append modes, this is an inappropriate value for the open mode and the Python interpreter will raise the ValueError.

Example

Let’s look at an example where we try to open a file with both read and write mode specified.

We will open a file called celeb_names.txt containing celebrity names

Leonardo DiCaprio
Michael Jordan
Franz Kafka
Mahatma Gandhi
Albert Einstein

Then, we will use the file method write() to write an additional celebrity name to the file.

with open('celeb_names.txt', 'rw') as f:

    lines = f.readlines()

    for line in lines:

        print(line)

    f.write('Pam Grier'+'\n')

    lines = f.readlines()

Let’s run the code to see what happens:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Input In [3], in <cell line: 1>()
----> 1 with open('celeb_names.txt', 'rw') as f:
      2     lines = f.readlines()
      3     for line in lines:

ValueError: must have exactly one of create/read/write/append mode

The error occurs because we specified an incorrect mode for the open() function, ‘rw‘.

Solution

If we want to open a file for both reading and writing, we can use the ‘r+‘ mode instead.

with open('celeb_names.txt', 'r+') as f:

    lines = f.readlines()

    for line in lines:

        print(line)

    f.write('Pam Grier'+'\n')

Once, we run the code we will have a file containing the additional celebrity name. Let’s open the file and print the lines to the console:

with open('celeb_names.txt', 'r') as f:

    lines = f.readlines()

    for line in lines:

        print(line)
Leonardo DiCaprio

Michael Jordan

Franz Kafka

Mahatma Gandhi

Albert Einstein

Pam Grier

We successfully wrote the additional line to the file.

What does the + mean in open()?

There are additional ways to perform reading and writing:

  • The r+ mode throws an error if the file does not exist or opens an existing file without truncating it for reading and writing and positions the stream at the beginning of the file.
  • The w+ mode creates a new file or truncates (overwrites) an existing file, then opens it for reading and writing with the file pointer position at the beginning of the file.
  • The a+ mode creates a new file or opens an existing file for reading and writing, and the file pointer position is at the end of the file.

Summary

Congratulations on reading to the end of this tutorial!

For further reading on Python ValueErrors, go to the article:

To learn more about Python for data science and machine learning, go to the online courses page on Python for the most comprehensive courses available.

Have fun and happy researching!

Research Scientist at Moogsoft | + posts

Suf is a research scientist at Moogsoft, specializing in Natural Language Processing and Complex Networks. Previously he was a Postdoctoral Research Fellow in Data Science working on adaptations of cutting-edge physics analysis techniques to data-intensive problems in industry. In another life, he was an experimental particle physicist working on the ATLAS Experiment of the Large Hadron Collider. His passion is to share his experience as an academic moving into industry while continuing to pursue research. Find out more about the creator of the Research Scientist Pod here and sign up to the mailing list here!