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:
