How to open a file for both reading and writing?

bigredhat picture bigredhat · Jul 11, 2011 · Viewed 273.3k times · Source

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?

Answer

Flimm picture Flimm · Apr 12, 2013

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