Menu Close

How to open a file for both reading and writing with Python?

Sometimes, we want to open a file for both reading and writing with Python.

In this article, we’ll look at how to open a file for both reading and writing with Python.

How to open a file for both reading and writing with Python?

To open a file for both reading and writing with Python, we can call open with the 'r+' permission.

For instance, we write

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

to call open with the filename and the 'r+' permission to open the file at filename with read and write permission.

Then we call read to read the file in the with block.

And we call write to write the output to the file.

Conclusion

To open a file for both reading and writing with Python, we can call open with the 'r+' permission.

Posted in Python, Python Answers