Reading Files in Python
Learn how to open a file, read its contents and process file data using different Python methods.
What is Reading a File?
Reading a file means getting the data stored inside a file and using that data in a Python program.
Python provides the open() function to open
a file and different methods to read its contents.
Reading File Diagram
The basic process of reading a file is:
Python Program
Wants to read stored information.
Open File
Use
open()
Read Data
Use
read()
or other methods.
Process Data
Display or use the file content.
File Content
Data is available inside the Python program.
Step 1: Open a File
To read a text file, we can open it using
open() with "r" mode.
file = open("example.txt", "r")
Here:
-
example.txtis the file name. -
"r"means read mode. -
filestores the opened file object.
Step 2: Read the Complete File
The read() method reads the file content.
file = open("example.txt", "r")
data = file.read()
print(data)
file.close()
Suppose example.txt contains:
Hello Python
Welcome to File Handling
Output:
Hello Python
Welcome to File Handling
The complete file content is returned as one string.
Reading a File Using with
A better and safer way is to use the
with statement.
with open("example.txt", "r") as file:
data = file.read()
print(data)
When the with block finishes, Python
handles the file resource automatically.
Reading a Specific Number of Characters
We can pass a number to read() to read
only a specific number of characters.
with open("example.txt", "r") as file:
data = file.read(5)
print(data)
If the file starts with:
Hello Python
Output:
Hello
Here, only the first five characters are read.
Reading One Line Using readline()
The readline() method reads one line
from the file.
with open("example.txt", "r") as file:
line = file.readline()
print(line)
Suppose the file contains:
Python
Java
.NET
The first call to readline() reads:
Python
Reading Multiple Lines
We can call readline() multiple times.
with open("example.txt", "r") as file:
line1 = file.readline()
line2 = file.readline()
print(line1)
print(line2)
Each call moves the reading position to the next line.
Reading All Lines Using readlines()
The readlines() method reads all lines
and returns them as a list.
with open("example.txt", "r") as file:
lines = file.readlines()
print(lines)
For a file containing:
Python
Java
.NET
The result is similar to:
['Python\n', 'Java\n', '.NET']
Each item in the list represents a line.
Reading a File Line by Line Using a Loop
We can directly loop through a file object.
with open("example.txt", "r") as file:
for line in file:
print(line.strip())
This is useful when a file contains many lines and we want to process them one by one.
Using strip() While Reading
Lines read from a text file often contain a newline character.
We can use strip() to remove unwanted
spaces and newline characters.
with open("example.txt", "r") as file:
for line in file:
print(line.strip())
Handling File Not Found Error
If the file does not exist, Python can raise a
FileNotFoundError.
try:
with open("example.txt", "r") as file:
data = file.read()
print(data)
except FileNotFoundError:
print("File not found")
This prevents the program from stopping unexpectedly when the required file is missing.
Reading a File with Encoding
We can specify the text encoding while opening a file.
with open(
"example.txt",
"r",
encoding="utf-8"
) as file:
data = file.read()
print(data)
UTF-8 is a common text encoding and is useful when working with multilingual text.
Understanding the File Position
Python keeps track of the current position while reading a file.
with open("example.txt", "r") as file:
print(file.tell())
file.read(5)
print(file.tell())
The tell() method returns the current
position in the file.
Moving the File Position with seek()
The seek() method changes the current
reading position.
with open("example.txt", "r") as file:
print(file.read(5))
file.seek(0)
print(file.read(5))
Here seek(0) moves the reading position
back to the beginning of the file.
Reading a Text File
Example file:
students.txt
Rahul
Priya
Amit
Sneha
Python program:
with open("students.txt", "r") as file:
for student in file:
print(student.strip())
Output:
Rahul
Priya
Amit
Sneha
Store File Data in a List
We can store each line inside a Python list.
students = []
with open("students.txt", "r") as file:
for line in file:
students.append(line.strip())
print(students)
Output:
['Rahul', 'Priya', 'Amit', 'Sneha']
Count Number of Lines
count = 0
with open("students.txt", "r") as file:
for line in file:
count += 1
print("Total Lines:", count)
Output for the example file:
Total Lines: 4
Search for Text in a File
We can check whether a particular word exists in a file.
search_name = "Rahul"
with open("students.txt", "r") as file:
data = file.read()
if search_name in data:
print("Student found")
else:
print("Student not found")
Output:
Student found
read() vs readline() vs readlines()
| Method | Returns | Use |
|---|---|---|
read()
|
Complete content as a string | Read the whole file |
readline()
|
One line | Read one line at a time |
readlines()
|
List of lines | Read all lines as a list |
Best Practice for Reading Files
Step 1: Make sure the file path is correct.
↓
Step 2: Open the file in read mode.
↓
Step 3:
Use with whenever practical.
↓
Step 4: Choose the appropriate reading method.
↓
Step 5: Handle missing files and other exceptions.
Common Mistakes
- Giving an incorrect file path.
- Forgetting to use read mode when needed.
- Trying to read a file that does not exist.
-
Forgetting that
read()returns a string. - Forgetting to remove newline characters while processing individual lines.
Practice Programs
-
Create a file named
students.txtcontaining five student names. - Read and display the complete file.
- Read only the first line.
-
Read all lines using
readlines(). -
Print every line using a
forloop. - Count the total number of lines.
- Search for a specific student name in the file.
Summary
Python provides several ways to read file data.
The read() method reads the complete
content, readline() reads one line and
readlines() returns all lines as a list.
We can also loop through a file line by line.
The with statement is a convenient way
to work with files, and exceptions such as
FileNotFoundError can be handled when
the file is missing.