How to open a file in both read and append mode at the same time in one variable in python?

Question:

'r' will read a file, 'w' will write text in the file from the start, and 'a' will append. How can I open the file to read and append at the same time?

I tried these, but got errors:

open("filename", "r,a")

open("filename", "w")
open("filename", "r")
open("filename", "a")

error:

invalid mode: 'r,a'
Asked By: Baldau dhanoriya

||

Answers:

You can’t do that with a textfile. Either you want to read it or you want to write to it. The a or the r specifies a seek to a particular location in the file. Specifying both is asking open to point to two different locations in the file at the same time.

Textfiles in general can’t be updated in place. You can use a to add new stuff to the end but that is about it. To do what I think you want, you need to open the existing file in read mode, and open another, new file in write mode, and copy the data from the one to the other.

After that you have two files so you have to take care of deleting the old one. If that is troublesome, take a look at the module in-place.

The other alternative is to read the input file into memory, close and reopen it for writing, then write out a new version of the file. Then you don’t have to delete the old copy. But if something goes wrong in the middle you will have no old input file, because you deleted it, and no new output file either, because you didn’t successfully write it.

The reason for this is that textfiles are not designed for random access.

Answered By: BoarGules

You’re looking for the r+/a+/w+ mode, which allows both read and write operations to files.

With r+, the position is initially at the beginning, but reading it once will push it towards the end, allowing you to append. With a+, the position is initially at the end.

with open("filename", "r+") as f:
    # here, position is initially at the beginning
    text = f.read()
    # after reading, the position is pushed toward the end

    f.write("stuff to append")
with open("filename", "a+") as f:
    # here, position is already at the end
    f.write("stuff to append")

If you ever need to do an entire reread, you could return to the starting position by doing f.seek(0).

with open("filename", "r+") as f:
    text = f.read()
    f.write("stuff to append")

    f.seek(0)  # return to the top of the file
    text = f.read()

    assert text.endswith("stuff to append")

(Further Reading: What’s the difference between ‘r+’ and ‘a+’ when open file in python?)

You can also use w+, but this will truncate (delete) all the existing content.

Here’s a nice little diagram from another SO post:

Decision Tree: What mode should I use?

Answered By: TrebledJ
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.