File Handling

3 min read

Read, Write, and Manage Files Like a Pro

File handling allows Python programs to interact with external files β€” reading from them, writing data, and even modifying their contents. It’s an essential skill for real-world applications like report generators, data loggers, and simple databases.


πŸ“„ 1. Opening a File #

Python uses the built-in open() function to work with files.

file = open("data.txt", "r")  # 'r' is for read mode

πŸ›  File Modes: #

ModeDescription
rRead (default mode)
wWrite (overwrites file)
aAppend (adds to file)
xCreate (fails if file exists)
r+Read and write

πŸ“˜ 2. Reading From a File #

πŸ“Œ Read Entire File: #

file = open("data.txt", "r")
content = file.read()
print(content)
file.close()

πŸ“Œ Read Line-by-Line: #

file = open("data.txt", "r")
for line in file:
    print(line.strip())  # .strip() removes newline
file.close()

✍️ 3. Writing to a File #

Overwrite (write mode): #

file = open("log.txt", "w")
file.write("Welcome to the log file.\n")
file.write("Another line added.\n")
file.close()

Append (without erasing existing content): #

file = open("log.txt", "a")
file.write("Appending this line...\n")
file.close()

βœ… 4. Best Practice: with Statement #

Using with automatically closes the file after usage β€” cleaner and safer.

with open("data.txt", "r") as file:
    content = file.read()
    print(content)

# No need for file.close()

πŸ§ͺ 5. Checking If a File Exists (Optional) #

You can use the os module:

import os

if os.path.exists("data.txt"):
    print("File exists!")
else:
    print("File not found.")

πŸ”„ 6. Reading and Writing CSV Files #

For structured data, CSV is common:

import csv

# Writing CSV
with open("products.csv", "w", newline="") as file:
    writer = csv.writer(file)
    writer.writerow(["Name", "Price", "Stock"])
    writer.writerow(["Apple", "100", "50"])

# Reading CSV
with open("products.csv", "r") as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)

🧠 Real-World Use Case: Customer Order Tracker (Text File Based) #

Let’s build a simple system that:

  • Accepts customer name, product, and quantity
  • Saves order to a text file
  • Shows all previous orders

βœ… Code Example #

def take_order():
    name = input("Enter your name: ")
    product = input("Enter product name: ")
    qty = input("Enter quantity: ")

    with open("orders.txt", "a") as file:
        file.write(f"{name} ordered {qty} x {product}\n")

    print("βœ… Order saved successfully!")

def show_orders():
    print("\nπŸ“¦ Previous Orders:")
    with open("orders.txt", "r") as file:
        for line in file:
            print(line.strip())

# Run Program
while True:
    print("\n--- Grocery Order System ---")
    print("1. Place Order")
    print("2. Show Orders")
    print("3. Exit")
    choice = input("Choose an option: ")

    if choice == "1":
        take_order()
    elif choice == "2":
        show_orders()
    elif choice == "3":
        break
    else:
        print("❌ Invalid choice. Try again.")

πŸ“¦ Sample Output #

--- Grocery Order System ---
1. Place Order
2. Show Orders
3. Exit
Choose an option: 1
Enter your name: Hannan
Enter product name: Eggs
Enter quantity: 12
βœ… Order saved successfully!

--- Grocery Order System ---
1. Place Order
2. Show Orders
3. Exit
Choose an option: 2

πŸ“¦ Previous Orders:
Hannan ordered 12 x Eggs

🧠 Key Takeaways #

ConceptSummary
open()Use to open a file with a mode
Read Modesr, readline(), readlines()
Write Modesw, a, and write()
withAuto closes file (best practice)
CSVGreat for tabular data
Real-WorldText-based customer order tracker

πŸ”š Wrap Up #

File handling gives your programs memory β€” the ability to store and retrieve data long after they run. You’ll use it in logging, settings files, exports, backups, and more.


πŸ”œ Coming Up Next: #

Error Handling & Debugging in Python
Learn how to use try, except, and other error control tools to make your programs more reliable β€” with a Login Authenticator use case.

Want me to write that chapter as well? Just say the word β€” I’ll keep the series going!

Updated on June 9, 2025