Reading Files in Python
-
This lesson explains how to open and read data from files in Python.
What is File Handling?
File handling allows a program to read data from files and write data into files.
👉 Files are used to store data permanently.
Examples:
Text files (.txt)
Data files
Log files
Images (binary files)
Why Do We Need File Handling?
File handling helps to:
Store data permanently
Read large data efficiently
Share data between programs
Handle real-world applications
File Modes in Python
When opening a file, we must specify a mode.
Text Mode (t) – Default Mode
Used for text files
Reads data as string
Default mode in Python
Binary Mode (b)
Used for non-text files
Reads data as bytes
Used for images, audio, video
Opening Files in Python
open() Function
file = open("filename", "mode")
Opening a Text File
This program opens a file in read text mode.
file = open("data.txt", "r")
print("File opened successfully")
file.close()
Reading Entire File
Using read()
The read() method reads the entire content of the file.
Reading Entire File Using read()
This program reads and prints the complete content of the file.
file = open("data.txt", "r")
content = file.read()
print(content)
file.close()
Reading Line by Line
Method 1: readline()
Reads one line at a time.
Reading One Line Using readline()
This program reads only the first line of the file.
file = open("data.txt", "r")
line = file.readline()
print(line)
file.close()
Method 2: readlines()
Reads all lines and stores them in a list.
Reading Lines Using readlines()
This program reads all lines and prints them as a list.
file = open("data.txt", "r")
lines = file.readlines()
print(lines)
file.close()
- Method 3: Reading File Using Loop
Reading File Using for Loop
This program reads and prints each line one by one.
file = open("data.txt", "r")
for line in file:
print(line)
file.close()
Reading Binary Files
When to Use Binary Mode?
Binary mode is used for:
Images
PDFs
Audio / video files
Reading Binary File
This program opens a binary file and reads its content.
file = open("image.jpg", "rb")
data = file.read()
print(data)
file.close()
Using with Statement
Why Use with?
Automatically closes file
Safer and cleaner code
Using with Statement
This program reads file content without manually closing it.
with open("data.txt", "r") as file:
content = file.read()
print(content)