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: #
Mode | Description |
---|---|
r | Read (default mode) |
w | Write (overwrites file) |
a | Append (adds to file) |
x | Create (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 #
Concept | Summary |
---|---|
open() | Use to open a file with a mode |
Read Modes | r , readline() , readlines() |
Write Modes | w , a , and write() |
with | Auto closes file (best practice) |
CSV | Great for tabular data |
Real-World | Text-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 usetry
,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!