What is File Handling in Python?
File handling allows a Python program to store data permanently in files instead of keeping everything only in memory. Python provides simple functions and methods to create, read, write, append, and manage files.
Open a file using Python's open() function.
Read existing data from text or other supported files.
Create a new file or replace existing file contents.
Add new information without deleting existing content.
Python uses the open() function to open a file.
The basic syntax is:
file = open("data.txt", "r")
Here, data.txt is the file name and
"r" means read mode.
Python provides different modes depending on what you want to do with the file.
| Mode | Purpose |
|---|---|
r |
Read an existing file. |
w |
Write data. Creates a file or replaces existing content. |
a |
Append data to the end of a file. |
x |
Create a new file and fail if it already exists. |
r+ |
Read and write an existing file. |
b |
Binary mode. |
The read() method reads the complete contents
of a file.
file = open("employees.txt", "r")
content = file.read()
print(content)
file.close()
Rahul - Developer
Priya - Tester
Amit - Manager
The readline() method reads one line at a time.
file = open("employees.txt", "r")
line = file.readline()
print(line)
file.close()
Rahul - Developer
readlines() returns all lines as a list.
file = open("employees.txt", "r")
lines = file.readlines()
for line in lines:
print(line.strip())
file.close()
Rahul - Developer
Priya - Tester
Amit - Manager
The w mode writes data to a file. If the file
does not exist, Python creates it.
file = open("welcome.txt", "w")
file.write("Welcome to Python File Handling!")
file.close()
Welcome to Python File Handling!
w mode replaces
its previous contents.
The a mode adds new data at the end of the
existing file.
file = open("employees.txt", "a")
file.write("\nNeha - HR")
file.close()
Rahul - Developer
Priya - Tester
Amit - Manager
Neha - HR
The recommended way to work with files is using
with open(). Python automatically closes the
file after the block finishes.
with open("employees.txt", "r") as file:
content = file.read()
print(content)
A school application can store student information in a text file.
student = {
"name": "Rahul",
"age": 21,
"course": "Python"
}
with open("student.txt", "w") as file:
file.write(f"Name: {student['name']}\n")
file.write(f"Age: {student['age']}\n")
file.write(f"Course: {student['course']}\n")
print("Student record saved successfully.")
Student record saved successfully.
Applications often store login activity in log files for auditing and troubleshooting.
username = "rahul"
with open("login.log", "a") as file:
file.write(f"User {username} logged in successfully.\n")
print("Login activity recorded.")
Login activity recorded.
A banking application can maintain a simple transaction history using a file.
amount = 5000
account = "ACC1001"
with open("transactions.txt", "a") as file:
file.write(
f"Account: {account}, Deposit: ₹{amount}\n"
)
print("Transaction recorded.")
Transaction recorded.
An online shopping application can save order information into a file.
order_id = "ORD1001"
product = "Laptop"
price = 55000
with open("orders.txt", "a") as file:
file.write(
f"{order_id} | {product} | ₹{price}\n"
)
print("Order saved successfully.")
Order saved successfully.
The os.path.exists() function can be used to
check whether a file exists.
import os
filename = "employees.txt"
if os.path.exists(filename):
print("File exists.")
else:
print("File does not exist.")
File exists.
The x mode creates a new file. If the file
already exists, Python raises an error.
try:
with open("new_report.txt", "x") as file:
file.write("Monthly Report")
print("File created successfully.")
except FileExistsError:
print("File already exists.")
File created successfully.
An attendance system can append an employee's attendance information every day.
employee_id = "EMP101"
date = "2026-09-20"
status = "Present"
with open("attendance.txt", "a") as file:
file.write(
f"{employee_id} | {date} | {status}\n"
)
print("Attendance saved.")
Attendance saved.
When a file does not exist, opening it in read mode raises
FileNotFoundError. We can handle it using
try-except.
try:
with open("customer.txt", "r") as file:
data = file.read()
print(data)
except FileNotFoundError:
print("Customer file was not found.")
Customer file was not found.
Python can provide information such as file name, mode, and whether the file is closed.
file = open("data.txt", "r")
print("File name:", file.name)
print("File mode:", file.mode)
print("Is closed:", file.closed)
file.close()
print("Is closed:", file.closed)
File name: data.txt
File mode: r
Is closed: False
Is closed: True
Binary mode is useful for files such as images, PDFs, audio, and other non-text data.
with open("photo.jpg", "rb") as file:
data = file.read()
print("Binary data loaded.")
print("Bytes:", len(data))
Binary data loaded.
Bytes: 245678
A binary file can be copied by reading its bytes and writing them into another file.
with open("original.jpg", "rb") as source:
data = source.read()
with open("backup.jpg", "wb") as destination:
destination.write(data)
print("File copied successfully.")
File copied successfully.
The following example demonstrates how a small application can save customer records into a file and later display them.
def add_customer(customer_id, name, phone):
with open("customers.txt", "a") as file:
file.write(
f"{customer_id},{name},{phone}\n"
)
print("Customer added successfully.")
def show_customers():
try:
with open("customers.txt", "r") as file:
print("\nCustomer Records:")
for line in file:
customer_id, name, phone = line.strip().split(",")
print(
f"ID: {customer_id} | "
f"Name: {name} | "
f"Phone: {phone}"
)
except FileNotFoundError:
print("No customer records found.")
add_customer("C101", "Rahul", "9876543210")
add_customer("C102", "Priya", "9123456780")
show_customers()
Customer added successfully.
Customer added successfully.
Customer Records:
ID: C101 | Name: Rahul | Phone: 9876543210
ID: C102 | Name: Priya | Phone: 9123456780
-
Prefer
with open()for automatic file closing. -
Choose the correct file
modebefore opening a file. -
Use
awhen existing data must be preserved. -
Use
wcarefully because it replaces existing content. -
Handle
FileNotFoundErrorwhen reading files that may not exist. -
Use binary modes such as
rbandwbfor binary files. - Use appropriate file paths instead of relying on the current directory.
-
For structured application data, consider formats such as
JSONorCSV.
Use open() to access a file.
Use read(), readline(), or iteration.
Use write() to store data.
Use a mode to add data without replacing existing content.
Use close() when manually managing files.
Prefer with open() for safe automatic cleanup.
Python File Handling
Open • Read • Write • Append • Manage Files with Python