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

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)

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))

Tags:

Python