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 file.py and run it.

#!/usr/bin/env python

filename = "file.py"

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

print(content)

You should see

Alternative:
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 = "file.py"

infile = open(filename, 'r')
data = infile.read()
infile.close()

print(data)

Exercises

Try the exercises below

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

Answers

Dictionary
Write file

Be First to Comment

    Leave a Reply