How to Open a File for Both Reading and Writing in Python

To open a file with the ability to both read and write to it, use the Python open() function and set the mode to r+.


The open() Function Syntax

open() takes two arguments, the first is the name/location of the file to open and the second is the mode.


open(filename, mode)


Read and Write to File Python Example

To demonstrate using r+ mode, let's open an existing file and append a new line to it.


Some existing content.
Another line of content.
new_line = 'New line to prepend.\n'

with open('file.txt', 'r+') as file:
  content =
  file.write(new_line + content)