Skip main navigation

Reading from a file

Learn how to read from a text file in Python and iterate over the content of the file to print each line of text.
Robot reading a Word document

In the previous step you learnt how to write data to a file, but how can you read data from a file?

Files can store lots of useful data. For example, a file can be used to record the time and temperature for a weather station project. This data can then be used in a spreadsheet to graphically chart the data. This data would be worthless without a means to read and use the data. It is like owning a book which is never read: the knowledge is contained within, but never used.

Python and other programming languages can read data from a file in much the same manner as data is written to it.

Using a text editor, create a list of fruits and vegetables and save it as a text file called food.txt.

Apples
Oranges
Bananas
Tomatoes
Cucumber
Carrots
Peas

Create a new program and save it as food_read.py.

This program will read the contents of the file food.txt and print it to the screen.

Just as in the previous step, open the file and use f as a reference to work with the file.

Note: You need to use ‘read’ mode by using the parameter r instead of w (write) or a (append).

f = open("food.txt","r")

Next, read the contents of the file into a variable called data and print it.

data = f.read()
print(data)

Don’t forget to close the file.

f.close()

Leaving files open can cause data loss and can also prevent access when files are used by multiple concurrent users.

Run the program. Python will print the list all at once as a multi-line string showing each item on its own line.

Iterating over the file contents

Sometimes it can be useful to iterate over the contents of a file, reading the contents line by line.

The file is opened in the same manner as before.

f = open("food.txt", "r")

Using a for loop, the contents of the file f can be read line by line. Each time through the loop a new line from the file is stored in the variable line and then printed to the screen.

for line in f:
print(line)

Tip: for loops are loops that iterate a set number of times. This code will read each line from the file until it reaches the end of the file, when the for loop terminates.

Once again, it is important to close the file.

f.close()

Using a with statement

Notice how you have to close the file each time your program finishes. Ensuring that the file is opened and closed correctly is good file management as it reduces the risk of data loss. This is good practice and Python has built-in functions to simplify this.

Using a with statement you can open a file, do whatever you want with it, and then automatically close it.

The with statement also provides a means to manage any errors, for example if the file is not present or the file name is incorrect. It also provides automated cleanup, ensuring that a file is closed correctly when it is no longer needed.

This program will open a file and store it in the variable f, read the contents of the file to the variable data, and then print it to the screen.

with open("test.txt") as f:
data = f.read()
print(data)

Note: No code is needed to close the file, as the with statement handles closing the file once the contents have been read.

In the comments section discuss which data type data is, and if you can think of any situations where you might not want this to be the case.

This article is from the free online

Programming 103: Saving and Structuring Data

Created by
FutureLearn - Learning For Life

Reach your personal and professional goals

Unlock access to hundreds of expert online courses and degrees from top universities and educators to gain accredited qualifications and professional CV-building certificates.

Join over 18 million learners to launch, switch or build upon your career, all at your own pace, across a wide range of topic areas.

Start Learning now