To read a file in Python the
open() function is used to access the file, and the
readlines() functions return the contents of that file. Finally, the
close() method is used to close a file.
Python is a useful programming language to use if you want to process data. The language has several built-in functions that make it easy to read, write, and manipulate data or files.
Let’s say that you have a list of employee names, and you want to check if a user’s name is on that list. You could save the list of employee names as a file, then use Python to read that file and check if the employee’s name is stored within that file.
In this tutorial, we are going to explore the basics of reading files in Python. To start, we will discuss how to open and access a file. Then we will go on to explore how to read a file in Python.
Opening a File in Python
The first step to reading a file in Python is to open the file you want to read. Just like you would when you want to read a file on your computer, you need to tell Python the name of the file you want your program to access.
To read a file, you must first tell Python where that file resides. You can do so by specifying the path of the file and declaring it within a variable. Here’s an example of creating a variable that stores the location of a file:
filename = "/users/career_karma/names.txt"
Now we have declared the path for our file; we can open it. Python has a built-in
open() function that can open a file. The function returns a file object, which you can then read, update, and manipulate.
Here’s the syntax for opening a file in Python:
names_file = open(filename, 'r')
The above line of code opens the file at the path we have defined above.
r flag at the end of the
open() function tells Python that we only want to read our file, but we could change it if we tried to edit our file. Here’s a list of Python flags that we use with
r: Read a file
w: Write to a file
x: Create and write to a file
a: Append to a file
r+: Read and write to a file
Python Read File
Now that our file is open, we can read it through Python. There are three functions that we can use to read data from a file, which are as follows:
read(): Returns the contents of a file
readline(): Returns the next line of a file
readlines(): Returns a list of lines in a file
Let’s break down how each of these works. The
read() method can return the entire contents of a file as a string. Here’s an example of
read() operating on a file that contains a list of names:
path = "/users/career_karma/names.txt" names_file = open(path, 'r') print(names_file.read())
Our program returns the following:
As you can see, the
read() method returned everything within our
names file, including the newline characters at the end of our string.
readline() function returns the next line of a file. The function returns the text and the newline character at the end of the file. The following code will read the first line in our file:
Our code returns:
If we wanted to read the first and second lines of our existing file, we would need to use the
readline() function again, like this:
names_file = open(path, 'r') print(names_file.readline()) print(names_file.readline())
Our code returns the following output:
readline() function can be useful if you want to read a file line by line. The function is commonly used within a
for loop to read multiple lines in a file, like this:
for i in range(0, 2): print(names_file.readline())
Our code returns the following:
readlines() method returns a list of the lines in a file. This function returns an array, and each item represents a single line within a file:
The program returns the following:
['Sally\n', 'Alex\n', 'Pamela\n', 'Jonas\n', 'Luke\n', 'Will']
It’s worth noting that once you have read a file, you can’t reread it. So, when you have read the file using
readlines(), trying to reread the file using any read file operation will return an empty string. If you want to read a file multiple times, you’ll need to open the file again and read it.
Python Close File
After you have read a file, you should close the file. Closing a file will free up the resources used by reading the file. We can use the
close() function to close our file safely.
Here’s an example of the
close() method being used to close a file:
path = "/users/career_karma/names.txt" names_file = open(path, 'r') print(names_file.read()) names_file.close()
Our code will open our file, read it, then close the file at the end of the program.
There is a more efficient way to close a file, though. Using
with statements, we can close files after the code in the
with block executes. Here’s an example of the
with statement reading a file, which will then close our file after the code within the
with statement has run:
path = "/users/career_karma/names.txt" with open(path) as names_file: print(names_file.read())
This code works in precisely the same way as our code does above and will close our file automatically after the
print(names_file.read()) line of code has executed.
Storing data in files is common practice in Python, and allows you to keep track of specific data. You can use the
readlines() functions to read certain parts of your file, and manipulate the data depending on your needs. Today, we covered how to open a file, read it using specific methods, and how to close it in Python.
Now you’re ready to open and read Python files like an expert!