Python Reading Files
Table of Contents
In the last lesson, we learned about Python Introduction to Files. After learning the basics of file handling, let us focus on reading files in Python. Reading files is one of the most common tasks in programming. We might need to read a config file, a list of names, or a log file.
In this tutorial, we will learn how to read files using read(), readline(), and readlines(). We will also see how to loop through a file line by line.
π How to Open a File for Reading in Python
Before we can read a file, we need to open it in read mode. We use the open() function with "r".
file = open("example.txt", "r")Now file is a file object. We can use it to read the contents.
But remember, we need to close it when we are done.
file.close()Or better, use the with statement. It closes the file automatically.
with open("example.txt", "r") as file: # read the file here passWe will use with in all our examples. It is the safe way.
π§© How to Read the Whole File with read()
The read() method reads the entire file and returns it as a single string.
Letβs say we have a file called greeting.txt with this content:
Hello, world!This is a test file.Now we write a program to read it.
with open("greeting.txt", "r") as file: content = file.read() print(content)Output
Hello, world!This is a test file.The read() method gives us the whole file as one string. We can then print it, search it, or do anything else with it.
If we want to know how many characters are in the file, we can use len().
with open("greeting.txt", "r") as file: content = file.read() print(len(content))Output
35That includes every character, including spaces and newlines.
π§ How to Read One Line with readline()
The readline() method reads one line at a time. Each time we call it, it gives us the next line.
with open("greeting.txt", "r") as file: line1 = file.readline() line2 = file.readline() print(line1) print(line2)Output
Hello, world!
This is a test file.Notice the blank line between them? That is because each line already has a newline character at the end. And print() adds another one.
We can use strip() to remove the extra newline.
with open("greeting.txt", "r") as file: line1 = file.readline().strip() line2 = file.readline().strip() print(line1) print(line2)Output
Hello, world!This is a test file.Now it looks clean.
If we call readline() after the end of the file, it returns an empty string.
with open("greeting.txt", "r") as file: print(file.readline()) # Hello, world! print(file.readline()) # This is a test file. print(file.readline()) # (empty string)That is useful for loops. We can keep reading until we get an empty string.
π‘ How to Read All Lines with readlines()
The readlines() method reads all lines and returns them as a list of strings.
with open("greeting.txt", "r") as file: lines = file.readlines() print(lines)Output
['Hello, world!\n', 'This is a test file.\n']Each line includes the newline character. We can loop through the list and print each line.
with open("greeting.txt", "r") as file: lines = file.readlines() for line in lines: print(line.strip())Output
Hello, world!This is a test file.π§ͺ How to Loop Through a File in Python
We do not always need readlines(). We can loop through the file object directly. It gives us one line at a time.
with open("greeting.txt", "r") as file: for line in file: print(line.strip())Output
Hello, world!This is a test file.This is the most Pythonic way to read a file line by line. It is clean and efficient.
π Python Read File Example
Letβs read a file of names and greet each person.
with open("names.txt", "r") as file: for line in file: name = line.strip() if name: print(f"Hello, {name}!")If names.txt contains:
AlexSamJohnThe output is:
Hello, Alex!Hello, Sam!Hello, John!That is a simple way to process a list of items from a file.
βοΈ How to Read a Specific Number of Characters in Python
The read() method can take an argument. It reads that many characters.
with open("greeting.txt", "r") as file: first_five = file.read(5) print(first_five)Output
HelloIf we call read(5) again, it reads the next 5 characters.
with open("greeting.txt", "r") as file: print(file.read(5)) print(file.read(5))Output
Hello, worThis is useful when we want to process a file in chunks.
π How to Check if a File Exists Before Reading in Python
If we try to read a file that does not exist, we get a FileNotFoundError.
with open("missing.txt", "r") as file: content = file.read()Output
FileNotFoundError: [Errno 2] No such file or directory: 'missing.txt'We can handle this with a try-except.
try: with open("missing.txt", "r") as file: content = file.read() print(content)except FileNotFoundError: print("File not found")Output
File not foundThat way our program does not crash.
π§ Common Mistakes When Reading Files in Python
β Mistake 1: Forgetting to close the file
file = open("data.txt", "r")content = file.read()# forgot to closeFix: Use with or remember to call close().
π« Mistake 2: Using readline() after the end of the file
with open("data.txt", "r") as file: file.read() line = file.readline() # returns empty stringOnce the file is read, the file pointer is at the end. So readline() returns nothing.
Fix: Reopen the file or use seek(0) to go back to the start.
with open("data.txt", "r") as file: file.read() file.seek(0) line = file.readline()π Mistake 3: Not handling missing files
with open("missing.txt", "r") as file: content = file.read()This crashes if the file does not exist.
Fix: Use a try-except block.
π Mistake 4: Reading a large file all at once
with open("huge_file.txt", "r") as file: content = file.read()If the file is very large, this uses a lot of memory.
Fix: Read line by line instead.
with open("huge_file.txt", "r") as file: for line in file: process(line)Next, we will learn Python Writing Files, so our programs can save new information into files instead of only reading what is already there.