What are Read and Write Operations?
File read and write operations allow Python applications to store information permanently. A program can write new data into a file, read existing information, or append new records without deleting previous data.
Use w mode to create a file or replace
existing content.
Use r mode to retrieve existing file data.
Use a mode to add information at the end
of a file.
Use appropriate read/write operations to modify stored application data.
Use open() with "w" mode and the
write() method to store data.
file = open("message.txt", "w")
file.write("Hello, welcome to Python!")
file.close()
Hello, welcome to Python!
Use "r" mode and the read()
method to read the complete file.
file = open("message.txt", "r")
data = file.read()
print(data)
file.close()
Hello, welcome to Python!
The recommended approach is to use
with open(). Python automatically closes the
file when the block ends.
with open("message.txt", "w") as file:
file.write("Python makes file handling easy.")
with open("message.txt", "r") as file:
data = file.read()
print(data)
Python makes file handling easy.
Multiple lines can be written using newline characters
or the writelines() method.
employees = [
"Rahul - Developer\n",
"Priya - Tester\n",
"Amit - Manager\n"
]
with open("employees.txt", "w") as file:
file.writelines(employees)
Rahul - Developer
Priya - Tester
Amit - Manager
readline() reads one line from a file at a
time.
with open("employees.txt", "r") as file:
line = file.readline()
print(line.strip())
Rahul - Developer
readlines() returns the file's lines as a
list.
with open("employees.txt", "r") as file:
lines = file.readlines()
for line in lines:
print(line.strip())
Rahul - Developer
Priya - Tester
Amit - Manager
Iterating directly over the file is memory-friendly when processing large text files.
with open("employees.txt", "r") as file:
for line in file:
print(line.strip())
Rahul - Developer
Priya - Tester
Amit - Manager
Use "a" mode when you want to add new data
without removing existing content.
with open("employees.txt", "a") as file:
file.write("Neha - HR\n")
print("Employee added.")
Employee added.
A school or training application can write newly registered students into a file.
name = "Rahul"
course = "Python"
age = 21
with open("students.txt", "a") as file:
file.write(
f"{name} | {course} | {age}\n"
)
print("Student registered successfully.")
Student registered successfully.
An HR application can store employee details in a file and read them whenever required.
employee = {
"id": "EMP101",
"name": "Priya",
"department": "Testing"
}
with open("employee.txt", "w") as file:
file.write(f"ID: {employee['id']}\n")
file.write(f"Name: {employee['name']}\n")
file.write(f"Department: {employee['department']}\n")
with open("employee.txt", "r") as file:
print(file.read())
ID: EMP101
Name: Priya
Department: Testing
Banking applications can append deposits and withdrawals to a transaction history file.
account = "ACC1001"
transaction = "Deposit"
amount = 5000
with open("transactions.txt", "a") as file:
file.write(
f"{account} | {transaction} | ₹{amount}\n"
)
with open("transactions.txt", "r") as file:
history = file.read()
print(history)
ACC1001 | Deposit | ₹5000
An online shopping application can store order information and later read the order history.
order_id = "ORD1001"
product = "Laptop"
price = 55000
with open("orders.txt", "a") as file:
file.write(
f"{order_id} | {product} | ₹{price}\n"
)
with open("orders.txt", "r") as file:
for order in file:
print(order.strip())
ORD1001 | Laptop | ₹55000
Software applications often save login events in log files for tracking and troubleshooting.
username = "rahul"
with open("login.log", "a") as file:
file.write(
f"User {username} logged in successfully.\n"
)
with open("login.log", "r") as file:
logs = file.read()
print(logs)
User rahul logged in successfully.
Data entered by a user can be collected using
input() and stored in a file.
name = input("Enter your name: ")
email = input("Enter your email: ")
with open("users.txt", "a") as file:
file.write(
f"Name: {name}, Email: {email}\n"
)
print("User information saved.")
Enter your name: Rahul
Enter your email: rahul@example.com
User information saved.
You can pass a number to read() to retrieve
only that many characters.
with open("message.txt", "r") as file:
data = file.read(10)
print(data)
Hello, wel
tell() returns the current file position, while
seek() moves the file pointer.
with open("data.txt", "r") as file:
print("Position:", file.tell())
data = file.read(5)
print("Data:", data)
print("Position:", file.tell())
file.seek(0)
print("After seek:", file.tell())
Position: 0
Data: Hello
Position: 5
After seek: 0
When reading a file that may not exist, handle
FileNotFoundError 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.
The r+ mode allows both reading and writing
to an existing file.
with open("data.txt", "r+") as file:
data = file.read()
print("Existing data:")
print(data)
file.write("\nNew information added.")
r+ does not automatically erase the file.
The current file position determines where new data is
written.
An attendance application can save daily attendance and later read the records.
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 recorded.")
with open("attendance.txt", "r") as file:
print("\nAttendance Records:")
for line in file:
print(line.strip())
Attendance recorded.
Attendance Records:
EMP101 | 2026-09-20 | Present
This example combines writing, appending, reading, and error handling to build a simple customer record system.
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
| Mode | Operation | Existing Data | Creates File? |
|---|---|---|---|
r |
Read | Preserved | No |
w |
Write | Replaced | Yes |
a |
Append | Preserved | Yes |
r+ |
Read + Write | Preserved | No |
w+ |
Read + Write | Replaced | Yes |
a+ |
Read + Append | Preserved | Yes |
Use open() to access a file.
Use with open() for automatic cleanup.
Use read(), readline(),
or iteration depending on the requirement.
Remember that w mode replaces
existing content.
Use a when existing records must be
preserved.
Use exceptions such as
FileNotFoundError when appropriate.
Python Read & Write Files
Read • Write • Append • Update • Manage File Data with Python