How to read and write files in Python

Reading and writing files in Python can be done using the built-in open() function. The open() function takes two arguments, the file path and the mode. The mode can be ‘r’ for read-only, ‘w’ for write-only, ‘a’ for append, or ‘r+’ for read and write.

For example, to open a file for reading:

f = open(‘myfile.txt’, ‘r’)

To read the contents of the file:

contents = f.read()

To write to a file:

f = open(‘myfile.txt’, ‘w’)
f.write(‘Hello World!’)

To close the file:

f.close()