Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to open file in read and append mode in python at the same time in one variable

Tags:

python

file

'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'
like image 980
Baldau dhanoriya Avatar asked May 30 '19 15:05

Baldau dhanoriya


People also ask

How do you read and append file at the same time in python?

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.

How do I open file in read mode and append?

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.

Are both reading and writing possible after opening a file in Python?

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.


1 Answers

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")
like image 56
TrebledJ Avatar answered Sep 28 '22 10:09

TrebledJ