python – How to open a file for both reading and writing?

python – How to open a file for both reading and writing?

Heres how you read a file, and then write to it (overwriting any existing data), without closing and reopening:

with open(filename, r+) as f:
    data = f.read()
    f.seek(0)
    f.write(output)
    f.truncate()

Summarize the I/O behaviors

Mode r r+ w w+ a a+
Read + + + +
Write + + + + +
Create + + + +
Cover + +
Point in the beginning + + + +
Point in the end + +

and the decision branch

enter

python – How to open a file for both reading and writing?

r+ is the canonical mode for reading and writing at the same time. This is not different from using the fopen() system call since file() / open() is just a tiny wrapper around this operating system call.

Leave a Reply

Your email address will not be published. Required fields are marked *