π 1. Why File Handling Matters
In real life you constantly work with files:
- reading config files
- storing logs
- loading training data (CSV/JSON)
- saving model outputs
- writing results into text files
Python makes this very easy.
π 2. Opening a File (open())
Basic syntax:
file = open("filename.txt", "mode")
Modes you must know:
| Mode | Meaning |
|---|---|
"r" |
read (file must exist) |
"w" |
write (overwrite existing file) |
"a" |
append (add to existing file) |
"x" |
create file (error if exists) |
"b" |
binary mode (images, audio, etc.) |
"t" |
text mode (default) |
Real-life analogy
Mode = how you enter a room
-
r: you can only look -
w: you can rewrite everything -
a: you add more items without removing old ones
βοΈ 3. Writing to a File
Example: saving user notes
file = open("notes.txt", "w")
file.write("Remember to practice Python daily!")
file.close()
This creates/overwrites the file.
Append mode
file = open("notes.txt", "a")
file.write("\nToday's progress: Learned file handling.")
file.close()
π 4. Reading a File
Reading the whole file
file = open("notes.txt", "r")
content = file.read()
print(content)
file.close()
Reading line by line
file = open("notes.txt", "r")
for line in file:
print(line.strip())
file.close()
π 5. Important: Always Close the File
Not closing files can lock them or waste system resources.
Best practice: use with (autoclose)
with open("notes.txt", "r") as file:
content = file.read()
This automatically closes the file β ML/data engineers use this always.
π¦ 6. Real-Life Examples
π§Ύ Example 1: Saving user logs
with open("logs.txt", "a") as f:
f.write("User logged in at 9:00 PM\n")
π Example 2: Saving model predictions
predictions = [0.8, 0.2, 0.65]
with open("preds.txt", "w") as f:
for p in predictions:
f.write(str(p) + "\n")
π Example 3: Counting how many lines in a dataset
with open("data.txt") as f:
count = len(f.readlines())
print("Lines:", count)
π§ 7. Reading CSV Files (Without Pandas)
Real-life use: loading small datasets
with open("data.csv") as f:
for line in f:
values = line.strip().split(",")
print(values)
π§± 8. Writing to CSV Files
rows = [
["name", "age"],
["Ali", 25],
["Sara", 22]
]
with open("people.csv", "w") as f:
for r in rows:
f.write(",".join(map(str, r)) + "\n")
π 9. Working With JSON Files (Super Useful in ML)
Write JSON
import json
data = {"name": "Ali", "skills": ["py", "ml"]}
with open("info.json", "w") as f:
json.dump(data, f, indent=4)
Read JSON
with open("info.json") as f:
content = json.load(f)
print(content)
Real-life use:
- saving model configs
- storing hyperparameters
- reading APIs
πΌοΈ 10. Working With Binary Files (Images, audio)
with open("photo.jpg", "rb") as f:
data = f.read()
with open("copy.jpg", "wb") as f:
f.write(data)
π 11. Useful File-Related Operations (os module)
Check if file exists
import os
print(os.path.exists("notes.txt"))
Delete a file
os.remove("notes.txt")
List all files
print(os.listdir("."))
π§ͺ 12. Mini Exercises (Do these!)
Send your answers and Iβll check them.
Exercise 1
Write a note "Learning Python Files!" into learning.txt
Exercise 2
Read a file and print only lines that contain the word "error".
Exercise 3
Given a list of names, save each name on a new line in users.txt.
Exercise 4
Create a JSON file details.json containing:
- name
- age
- skills (list)
Exercise 5
Copy an image a.jpg into backup/a_backup.jpg.
Top comments (0)