How to open a file for both reading and writing?

PythonFileFile Io

Python Problem Overview


Is there a way to open a file for both reading and writing?

As a workaround, I open the file for writing, close it, then open it again for reading. But is there a way to open a file for both reading and writing?

Python Solutions


Solution 1 - Python

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()

Solution 2 - Python

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

Solution 3 - Python

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.

Solution 4 - Python

I have tried something like this and it works as expected:

f = open("c:\\log.log", 'r+b')
f.write("\x5F\x9D\x3E")
f.read(100)
f.close()

Where:

> f.read(size) - To read a file’s contents, call f.read(size), which > reads some quantity of data and returns it as a string.

And:

> f.write(string) writes the contents of string to the file, returning > None.

Also if you open Python tutorial about reading and writing files you will find that:

> 'r+' opens the file for both reading and writing. > > On Windows, 'b' appended to the mode opens the file in binary mode, so > there are also modes like 'rb', 'wb', and 'r+b'.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionbigredhatView Question on Stackoverflow
Solution 1 - PythonFlimmView Answer on Stackoverflow
Solution 2 - PythonAbstProcDoView Answer on Stackoverflow
Solution 3 - PythonAndreas JungView Answer on Stackoverflow
Solution 4 - PythonArtsiom RudzenkaView Answer on Stackoverflow