PYTHON READ & WRITE FILES

Learn how to read, write, append, update, and manage file data in Python using practical real-time examples.

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.

✍️ Write

Use w mode to create a file or replace existing content.

📖 Read

Use r mode to retrieve existing file data.

➕ Append

Use a mode to add information at the end of a file.

🔄 Update

Use appropriate read/write operations to modify stored application data.

Open
→
Write
→
Close
1. Writing Data to a File

Use open() with "w" mode and the write() method to store data.

Python
file = open("message.txt", "w")

file.write("Hello, welcome to Python!")

file.close()
File Content:
Hello, welcome to Python!
2. Reading Data from a File

Use "r" mode and the read() method to read the complete file.

Python
file = open("message.txt", "r")

data = file.read()

print(data)

file.close()
Output:
Hello, welcome to Python!
3. Using with open() for Read and Write

The recommended approach is to use with open(). Python automatically closes the file when the block ends.

Python
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)
Output:
Python makes file handling easy.
4. Writing Multiple Lines

Multiple lines can be written using newline characters or the writelines() method.

Python
employees = [
    "Rahul - Developer\n",
    "Priya - Tester\n",
    "Amit - Manager\n"
]

with open("employees.txt", "w") as file:
    file.writelines(employees)
File Content:
Rahul - Developer
Priya - Tester
Amit - Manager
5. Reading One Line at a Time

readline() reads one line from a file at a time.

Python
with open("employees.txt", "r") as file:
    line = file.readline()

print(line.strip())
Output:
Rahul - Developer
6. Reading All Lines

readlines() returns the file's lines as a list.

Python
with open("employees.txt", "r") as file:
    lines = file.readlines()

for line in lines:
    print(line.strip())
Output:
Rahul - Developer
Priya - Tester
Amit - Manager
7. Reading a File Using a for Loop

Iterating directly over the file is memory-friendly when processing large text files.

Python
with open("employees.txt", "r") as file:
    for line in file:
        print(line.strip())
Output:
Rahul - Developer
Priya - Tester
Amit - Manager
8. Appending Data to a File

Use "a" mode when you want to add new data without removing existing content.

Python
with open("employees.txt", "a") as file:
    file.write("Neha - HR\n")

print("Employee added.")
Output:
Employee added.
9. Real-Time Example: Student Registration

A school or training application can write newly registered students into a file.

Python
name = "Rahul"
course = "Python"
age = 21

with open("students.txt", "a") as file:
    file.write(
        f"{name} | {course} | {age}\n"
    )

print("Student registered successfully.")
Output:
Student registered successfully.
10. Real-Time Example: Employee Details

An HR application can store employee details in a file and read them whenever required.

Python
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())
Output:
ID: EMP101
Name: Priya
Department: Testing
11. Real-Time Example: Bank Transaction History

Banking applications can append deposits and withdrawals to a transaction history file.

Python
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)
Output:
ACC1001 | Deposit | ₹5000
12. Real-Time Example: E-Commerce Order File

An online shopping application can store order information and later read the order history.

Python
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())
Output:
ORD1001 | Laptop | ₹55000
13. Real-Time Example: Login Log

Software applications often save login events in log files for tracking and troubleshooting.

Python
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)
Output:
User rahul logged in successfully.
14. Writing User Input to a File

Data entered by a user can be collected using input() and stored in a file.

Python
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.")
Sample Run:
Enter your name: Rahul
Enter your email: rahul@example.com
User information saved.
15. Reading a Specific Number of Characters

You can pass a number to read() to retrieve only that many characters.

Python
with open("message.txt", "r") as file:
    data = file.read(10)

print(data)
Output:
Hello, wel
16. Using seek() and tell()

tell() returns the current file position, while seek() moves the file pointer.

Python
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())
Sample Output:
Position: 0
Data: Hello
Position: 5
After seek: 0
17. Handling File Not Found

When reading a file that may not exist, handle FileNotFoundError using try-except.

Python
try:
    with open("customer.txt", "r") as file:
        data = file.read()

    print(data)

except FileNotFoundError:
    print("Customer file was not found.")
Output:
Customer file was not found.
18. Read and Write Using r+ Mode

The r+ mode allows both reading and writing to an existing file.

Python
with open("data.txt", "r+") as file:
    data = file.read()

    print("Existing data:")
    print(data)

    file.write("\nNew information added.")
Note: r+ does not automatically erase the file. The current file position determines where new data is written.
19. Real-Time Example: Employee Attendance

An attendance application can save daily attendance and later read the records.

Python
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())
Output:
Attendance recorded.

Attendance Records:
EMP101 | 2026-09-20 | Present
20. Complete Real-Time Example: Customer Records

This example combines writing, appending, reading, and error handling to build a simple customer record system.

Python
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()
Output:
Customer added successfully.
Customer added successfully.

Customer Records:
ID: C101 | Name: Rahul | Phone: 9876543210
ID: C102 | Name: Priya | Phone: 9123456780
21. Read vs Write vs Append
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
22. Important Read & Write File Rules
1. Use open()

Use open() to access a file.

2. Prefer with

Use with open() for automatic cleanup.

3. Read Carefully

Use read(), readline(), or iteration depending on the requirement.

4. Write Carefully

Remember that w mode replaces existing content.

5. Use Append

Use a when existing records must be preserved.

6. Handle Errors

Use exceptions such as FileNotFoundError when appropriate.

💡 Key Idea: File handling allows applications to move beyond temporary in-memory data by storing information that can be read again later.

Python Read & Write Files

Read • Write • Append • Update • Manage File Data with Python