'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'
Print the contents of the files before appending using the read() function. Close both the files using the close() function. Open the first file in append mode and the second file in read mode. Append the contents of the second file to the first file using the write() function.
You're looking for the r+ or a+ mode, which allows read and write operations to files (see more). 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.
Use open() with the "r+" token to open a file for both reading and writing. Call open(filename, mode) with mode as "r+" to open filename for both reading and writing. The file will write to where the pointer is.
You're looking for the r+
or a+
mode, which allows read and write operations to files (see more).
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With