Wednesday, November 2, 2022

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

Issue

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

Solution

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?

(source)



Answered By - TrebledJ
Answer Checked By - David Goodson (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.