In Python, the open function can be used to open a files for writing, for reading and for append.

Python open a file for reading:

file = open('my_file.txt','r')

The r is implied, so it’s not needed.

file = open('my_file.txt')

open file for writing:

file = open('my_file.txt','w')

open for append:

file = open('my_file.txt','a')

Python write to file:

file.write('here's my text')

To read from a file:

text = file.read()

To close a file in Python:

file.close()

It’s always a good idea to close a file, even if it’s a the end of a script.

Read from a file line by line:

for line in open('my_file.txt'):

print(line)

Here’s an example to open a file and then write to it. Remember you need to then close the file before reading from it, otherwise it’ll throw an error.

>>> file = open('my_file.txt','w')

>>> file.write("here's my text")

>>> text = file.read()

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

IOError: File not open for reading

>>> file.close()