Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

I have a file that I open and i want to search through till I find a specific text phrase at the beginning of a line. I then want to overwrite that line with 'sentence'

sentence = "new text"           "
with open(main_path,'rw') as file: # Use file to refer to the file object
    for line in file.readlines():
        if line.startswith('text to replace'):
            file.write(sentence)

I'm getting:

Traceback (most recent call last):
 File "setup_main.py", line 37, in <module>
with open(main_path,'rw') as file: # Use file to refer to the file object
ValueError: must have exactly one of create/read/write/append mode

How can I get this working?

like image 621
user1592380 Avatar asked Dec 24 '18 20:12

user1592380


People also ask

How to fix Python ValueError must have exactly one of create/read/write/ append mode?

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.

What is the difference between'R'and'W'in'read and write'?

What I was trying to ask is: 'r' is the first letter of 'read' and 'w' the first letter of 'write' so 'r' and 'w' look natural to map to 'read' and 'write'. However, when it comes to 'read and write', Python uses 'r+' instead of 'rw'.

Why is the read/write/append function defined as R in Python?

It's just how the read/write/append function is configured in core python. Some will say that it has to do with old c-style fopen () directives 'r' 'w' 'r+' etc.


2 Answers

You can open a file for simultaneous reading and writing but it won't work the way you expect:

with open('file.txt', 'w') as f:
    f.write('abcd')

with open('file.txt', 'r+') as f:  # The mode is r+ instead of r
    print(f.read())  # prints "abcd"

    f.seek(0)        # Go back to the beginning of the file
    f.write('xyz')

    f.seek(0)
    print(f.read())  # prints "xyzd", not "xyzabcd"!

You can overwrite bytes or extend a file but you cannot insert or delete bytes without rewriting everything past your current position. Since lines aren't all the same length, it's easiest to do it in two seperate steps:

lines = []

# Parse the file into lines
with open('file.txt', 'r') as f:
    for line in f:
        if line.startswith('text to replace'):
            line = 'new text\n'

        lines.append(line)

# Write them back to the file
with open('file.txt', 'w') as f:
    f.writelines(lines)

    # Or: f.write(''.join(lines))
like image 166
Blender Avatar answered Oct 29 '22 01:10

Blender


You can't read and write to the same file. You'd have to read from main_path, and write to another one, e.g.

sentence = "new text"
with open(main_path,'rt') as file: # Use file to refer to the file object
    with open('out.txt','wt') as outfile:
        for line in file.readlines():
            if line.startswith('text to replace'):
                outfile.write(sentence)
            else:
                outfile.write(line)
like image 44
zyxue Avatar answered Oct 29 '22 02:10

zyxue