1️⃣ File I/O Recap
Humne beginner section me basic file read aur write dekha tha. Advanced level par hum zyada data formats aur efficient handling seekhenge.
# Simple text file write
with open("notes.txt", "w") as f:
f.write("AIkiPadhai is awesome!")
# Simple text file read
with open("notes.txt", "r") as f:
content = f.read()
print(content)
---
2️⃣ CSV Files (Comma Separated Values)
CSV files tab use hoti hain jab data tabular form me hota hai — jaise Excel ya Google Sheets.
Python me inke liye built-in csv module milta hai.
import csv
# Writing CSV
with open("students.csv", "w", newline='') as file:
writer = csv.writer(file)
writer.writerow(["Name", "Age"])
writer.writerow(["Rohan", 20])
writer.writerow(["Aisha", 22])
# Reading CSV
with open("students.csv", "r") as file:
reader = csv.reader(file)
for row in reader:
print(row)
👉 Output:
['Name', 'Age']
['Rohan', '20']
['Aisha', '22']
---
3️⃣ JSON Files (JavaScript Object Notation)
JSON ek popular format hai web data ke liye.
Python ke json module se aap easily JSON read aur write kar sakte ho.
import json
data = {
"name": "AIkiPadhai",
"topics": ["Python", "AI", "LLM"],
"active": True
}
# Write JSON
with open("data.json", "w") as f:
json.dump(data, f, indent=4)
# Read JSON
with open("data.json", "r") as f:
info = json.load(f)
print(info["topics"])
---
4️⃣ Pickle — Python Object Serialization 🧠
Pickle ka use hota hai Python objects (jaise list, dict, class objects) ko file me save karne ke liye. Baad me unhe directly load kar sakte ho bina recreate kiye.
import pickle
user = {"name": "Ravi", "score": 95}
# Save object
with open("user.pkl", "wb") as f:
pickle.dump(user, f)
# Load object
with open("user.pkl", "rb") as f:
loaded_user = pickle.load(f)
print(loaded_user)
⚠️ Note: Pickle files Python-specific hote hain — dusre languages ke saath compatible nahi.
---5️⃣ Working with Binary Files
Binary mode me hum non-text data handle karte hain jaise images, audio, ya custom binary data.
with open("image.jpg", "rb") as img:
data = img.read(100)
print(data[:20]) # first 20 bytes
---
6️⃣ Using pathlib for Modern File Handling
pathlib ek modern module hai jo file paths ke saath object-oriented way me kaam karta hai.
from pathlib import Path
# Path object banana
p = Path("notes.txt")
# File exists check karna
if p.exists():
print("File present hai ✅")
# Naya folder banana
new_dir = Path("backup")
new_dir.mkdir(exist_ok=True)
---
7️⃣ Real-life Example: Merge CSV Data
Maan lo aapke paas multiple CSV files hain aur aap unhe ek combined file me merge karna chahte ho.
import csv
from pathlib import Path
folder = Path("data")
output_file = Path("merged.csv")
with open(output_file, "w", newline="") as out:
writer = csv.writer(out)
writer.writerow(["Name", "Age"])
for file in folder.glob("*.csv"):
with open(file, "r") as f:
reader = csv.reader(f)
next(reader) # skip header
for row in reader:
writer.writerow(row)
print("All CSV files merged ✅")
---
💡 Summary
- CSV – tabular data
- JSON – structured web data
- Pickle – Python object storage
- pathlib – modern file handling
Ye sab data handling tools aapko real-world automation aur AI projects ke liye ready karte hain 🚀