Skip to content

Read file

Related course:

Read file

In Python you reading files is part of the standard library.  To read files, you can use the readlines() function. This will read a file line by line and store it into a list:

Type the code below, save it as and run it.

#!/usr/bin/env python

filename = ""

with open(filename) as f:
    content = f.readlines()


You should see

You may not always want to read a file line by line. Take for example, if your file does not have newlines or is a binary file. To read a file and store into a string, use the read() function instead:

#!/usr/bin/env python

filename = ""

infile = open(filename, 'r')
data =



Try the exercises below

1. Create a file that reads a text file from your computer


Write file
Published inUncategorized

Be First to Comment

    Leave a Reply