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

How to open a file for both reading and writing?


Here's 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 image description here


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.