The ability to work with external files is essential for any Python programmer. In this article we will look in detail at how to read from text files in Python. This can be a bit confusing at first as there are several ways to achieve the same result (as is often the case with programming), and also different requirements for the way the data is to be used when read. We will learn by doing hands-on exercises.
Setup
- Create a text file named
starwars_characters.txt
using Notepad, Notepad++ or another text-editing program. - Add the character names given below and then save the file. When saving it, create a new folder called
File Reading
and savestarwars_characters.txt
in that folder.
Darth Vader Obi-Wan Kenobi Han Solo Luke Skywalker Yoda R2-D2 Chewbacca Princess Leia Jabba the Hutt
- Create an empty python file called
file_reading.py
in the same folder!.
Now we are ready to begin coding.
The simple approach
If you are studying Computer Science you will need to be familiar with some form of pseudocode. The approach used below to read data from a text file is quite similar to what a pseudocode version would look like.
characters = []
fh = open('starwars_characters.txt', 'r') # fh is short for "file_handle."
for line in fh:
characters.append(line.strip()) # strip() removes the newline characters
fh.close() # This is important!
print(characters[5]) # Should print "Yoda"
Note the 'r'
in open('starwars_characters.txt', 'r')
is for “read mode.” We’ll study other modes later, but for now don’t worry too much about it – just type the code as given.
Once we have a working piece of code, there are often many refinements which can be made to “improve” it. However, be aware some of these refinements can come at the cost of clarity and ease of understanding/remembering.
Using with
Python provides a way of keeping a file open only as long as it is needed by using the keyword with
. This is considered better practice than the first approach where you have to remember to close the file “manually.”
characters = []
with open('starwars_characters.txt', 'r') as fh:
for line in fh:
characters.append(line.strip())
print(characters[5]) # Should print "Yoda"
An option to avoid – readlines()
We could achieve the same result using readlines()
. However this approach is not recommended as explained in this article. It is shown here for completeness, and so you can recognise it to avoid it.
characters = []
fh = open('starwars_characters.txt', 'r')
lines = fh.readlines()
for line in lines:
characters.append(line.strip())
print(characters[4]) # Should print "Yoda"
The most Pythonic way
Python programmers often pride themselves on how well they can “speak fluent Python,” using all the best practices and powerful shortcuts of the language. List comprehensions are a classic example of the Pythonic approach.
with open("starwars_characters.txt", "r") as fh:
characters = [line.strip() for line in fh]
print(characters[4]) # Should print "Yoda"
So there you have several ways to read data from an external file into a Python program. Depending on your goals, you should study and memorise some or all of them. For passing your GCSE Computer Science exam, I would recommend focusing on the first approach, whereas if you want to become a good Python programmer, you should study the others as well.
Hopefully that was helpful. Look out for future articles on file handling in Python.
Incorrect – doesn’t print “Yoda” as “Yoda is at index position 5!
Someone is awake! Fixed.