PYTHON FILE HANDLING

Learn how Python creates, opens, reads, writes, updates, and manages files using practical real-time examples.

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

Open a file using Python's open() function.

📖 Read

Read existing data from text or other supported files.

✍️ Write

Create a new file or replace existing file contents.

➕ Append

Add new information without deleting existing content.

Open
→
Read / Write
→
Close
1. Opening a File

Python uses the open() function to open a file. The basic syntax is:

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

Here, data.txt is the file name and "r" means read mode.

2. File Opening Modes

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.
3. Reading the Entire File

The read() method reads the complete contents of a file.

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

content = file.read()

print(content)

file.close()
Output:
Rahul - Developer
Priya - Tester
Amit - Manager
4. Reading One Line

The readline() method reads one line at a time.

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

line = file.readline()

print(line)

file.close()
Output:
Rahul - Developer
5. Reading All Lines with readlines()

readlines() returns all lines as a list.

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

lines = file.readlines()

for line in lines:
    print(line.strip())

file.close()
Output:
Rahul - Developer
Priya - Tester
Amit - Manager
6. Writing to a File

The w mode writes data to a file. If the file does not exist, Python creates it.

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

file.write("Welcome to Python File Handling!")

file.close()
File content:
Welcome to Python File Handling!
⚠️ Opening an existing file in w mode replaces its previous contents.
7. Appending Data to a File

The a mode adds new data at the end of the existing file.

Python
file = open("employees.txt", "a")

file.write("\nNeha - HR")

file.close()
Updated file:
Rahul - Developer
Priya - Tester
Amit - Manager
Neha - HR
8. Using with open()

The recommended way to work with files is using with open(). Python automatically closes the file after the block finishes.

Python
with open("employees.txt", "r") as file:
    content = file.read()
    print(content)
Benefit: The file is automatically closed, even if an error occurs inside the block.
9. Real-Time Example: Student Records

A school application can store student information in a text file.

Python
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.")
Output:
Student record saved successfully.
10. Real-Time Example: Login Activity Log

Applications often store login activity in log files for auditing and troubleshooting.

Python
username = "rahul"

with open("login.log", "a") as file:
    file.write(f"User {username} logged in successfully.\n")

print("Login activity recorded.")
Output:
Login activity recorded.
11. Real-Time Example: Bank Transaction Log

A banking application can maintain a simple transaction history using a file.

Python
amount = 5000
account = "ACC1001"

with open("transactions.txt", "a") as file:
    file.write(
        f"Account: {account}, Deposit: ₹{amount}\n"
    )

print("Transaction recorded.")
Output:
Transaction recorded.
12. Real-Time Example: E-Commerce Order History

An online shopping application can save order information into a file.

Python
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.")
Output:
Order saved successfully.
13. Checking Whether a File Exists

The os.path.exists() function can be used to check whether a file exists.

Python
import os

filename = "employees.txt"

if os.path.exists(filename):
    print("File exists.")
else:
    print("File does not exist.")
Output:
File exists.
14. Creating a New File with x Mode

The x mode creates a new file. If the file already exists, Python raises an error.

Python
try:
    with open("new_report.txt", "x") as file:
        file.write("Monthly Report")
        
    print("File created successfully.")

except FileExistsError:
    print("File already exists.")
Output:
File created successfully.
15. Real-Time Example: Employee Attendance

An attendance system can append an employee's attendance information every day.

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 saved.")
Output:
Attendance saved.
16. Handling File Not Found Errors

When a file does not exist, opening it in read mode raises FileNotFoundError. We can handle it 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.
17. Getting File Information

Python can provide information such as file name, mode, and whether the file is closed.

Python
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)
Output:
File name: data.txt
File mode: r
Is closed: False
Is closed: True
18. Working with Binary Files

Binary mode is useful for files such as images, PDFs, audio, and other non-text data.

Python
with open("photo.jpg", "rb") as file:
    data = file.read()

print("Binary data loaded.")
print("Bytes:", len(data))
Output:
Binary data loaded.
Bytes: 245678
19. Copying a File

A binary file can be copied by reading its bytes and writing them into another file.

Python
with open("original.jpg", "rb") as source:
    data = source.read()

with open("backup.jpg", "wb") as destination:
    destination.write(data)

print("File copied successfully.")
Output:
File copied successfully.
20. Complete Real-Time Example: Customer Management

The following example demonstrates how a small application can save customer records into a file and later display them.

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. File Handling Best Practices
  • Prefer with open() for automatic file closing.
  • Choose the correct file mode before opening a file.
  • Use a when existing data must be preserved.
  • Use w carefully because it replaces existing content.
  • Handle FileNotFoundError when reading files that may not exist.
  • Use binary modes such as rb and wb for binary files.
  • Use appropriate file paths instead of relying on the current directory.
  • For structured application data, consider formats such as JSON or CSV.
22. Important File Handling Rules
1. open()

Use open() to access a file.

2. Read

Use read(), readline(), or iteration.

3. Write

Use write() to store data.

4. Append

Use a mode to add data without replacing existing content.

5. Close

Use close() when manually managing files.

6. with

Prefer with open() for safe automatic cleanup.

Python File Handling

Open • Read • Write • Append • Manage Files with Python