Bro, sach bolu? Jab main pehli baar file handling padha tha na, mujhe laga “arre ye toh boring chapter hoga, files open karni hai, close karni hai — kya maza aayega?” 😅 But bhai, jab real projects banane start kiye na, tab samjha — yehi topic life saver hai! Matlab data save karna, load karna, aur errors handle karna — sab yahin se start hota hai.
Aaj tu seekhega:
- File open/read/write karna
- CSV aur JSON files ke saath kaam karna
- Errors ko handle karna like a pro (try, except, finally, raise)
- Aur last me ek mini To-Do list project jisme sab kuch practical use hoga 💪
Ready? Chalo shuru karte hain bro.
Opening, Reading & Writing Files – Data ka Real Game 🎮
Soch — tu ek game bana raha hai, aur uska high score store karna hai. Agar tu har baar program run karne pe score wipe kar dega toh kya fayda? Yahan aata hai file handling ka power.
Python me file ke saath deal karne ke liye simple syntax hota hai:
file = open("data.txt", "r")
content = file.read()
print(content)
file.close()
Mode ka Scene 🎬
Jab tu file open karta hai, tab ek “mode” batata hai — basically kya karna hai file ke saath.
r
– Read mode (sirf padhna)w
– Write mode (purani file overwrite kar dega)a
– Append mode (file ke end me likhta hai)r+
– Read + Write donox
– New file banata hai (agar pehle se hai, error dega)
Example:
# Writing to a file
file = open("notes.txt", "w")
file.write("Python rocks bro! 💥")
file.close()
# Reading back
file = open("notes.txt", "r")
print(file.read())
file.close()
Dekha? Ek dum simple. Lekin ek golden rule — File open kiya toh close bhi karna bhai! Nahi toh kabhi kabhi system resources leak ho jaate hain (aur tu bolega “yeh kya hua?” 😅).
Using “with” Statement – Clean & Smart Way 🧹
Python me ek smart shortcut bhi hai — with open()
block automatically file close kar deta hai, chahe error aaye ya nahi.
with open("data.txt", "r") as f:
print(f.read())
Bas ho gaya. “with” use kar, aur tension-free reh. Isse code clean dikhta hai aur error handling easy ho jaati hai.
Writing, Appending & Reading Line by Line 📜
Kabhi kabhi tu poori file nahi, sirf line-by-line read karna chahta hai. Jaise ek diary ke pages flip karna.
with open("story.txt", "w") as f:
f.write("Once upon a time...\n")
f.write("There was a Python developer named Ritik 🐍\n")
with open("story.txt", "r") as f:
for line in f:
print(line.strip())
.strip()
lagana mat bhoolna — warna unwanted blank lines aa jaayengi.
Working with CSV Files – Data Analyst Vibes 📊
Ab maan le tu ek Excel type data handle kar raha hai — like player scores, employee records, etc. CSV (Comma Separated Values) file is perfect for that.
Python ka csv
module kaafi helpful hai.
import csv
# Writing CSV
with open("players.csv", "w", newline="") as file:
writer = csv.writer(file)
writer.writerow(["Name", "Score"])
writer.writerow(["Ritik", 120])
writer.writerow(["Aman", 95])
# Reading CSV
with open("players.csv", "r") as file:
reader = csv.reader(file)
for row in reader:
print(row)
Output:
['Name', 'Score']
['Ritik', '120']
['Aman', '95']
Simple aur real-life use ke laayak. Yehi file format Excel aur Google Sheets me bhi open hota hai.
Working with JSON Files – Web Developer ka Dost 🌍
JSON basically data ka universal format hai — APIs, databases, mobile apps — sab use karte hain.
Python me json
module is your best buddy.
import json
data = {
"name": "Ritik",
"age": 21,
"skills": ["Python", "Game Dev", "SEO"]
}
# Writing JSON
with open("data.json", "w") as file:
json.dump(data, file)
# Reading JSON
with open("data.json", "r") as file:
content = json.load(file)
print(content)
Output:
{'name': 'Ritik', 'age': 21, 'skills': ['Python', 'Game Dev', 'SEO']}
JSON ka magic yehi hai — structure clean, readable aur universal. Web APIs ke liye ye must-know concept hai bro.
Error Handling in Python – Jab Code Galti Kare 😅
Ab maan le tu file open kar raha hai jo exist hi nahi karti. Program crash ho jaayega na? Bas yahan aata hai — try-except ka magic.
Basic Example
try:
f = open("unknown.txt")
print(f.read())
except FileNotFoundError:
print("Bhai file hi nahi mili 😅")
Output:
Bhai file hi nahi mili 😅
Ab code crash nahi hua — handle ho gaya sweetly 😎
Multiple Exceptions
try:
num = int(input("Enter number: "))
result = 10 / num
except ValueError:
print("Bhai number likh, string nahi 😅")
except ZeroDivisionError:
print("0 se divide karega toh duniya khatam 😂")
Python me har error ka naam alag hota hai — bas sahi exception pakad le.
finally – Jo Hamesha Chalega 🔄
Bro, dekho na, finally block ka kaam simple hai – chahe code me gadbad ho ya na ho, ye hamesha chalega. Jaise system shutdown se pehle last cleaning karte hain 😎
try:
f = open("notes.txt", "r")
print(f.read())
except:
print("Arre yaar, kuch toh ulta-pulta ho gaya 😅")
finally:
f.close()
print("File safely close ho gayi bro ✅")
raise – Apni Error Fenkh De 💣
Bro, kabhi apne hisaab ki error bhi fenkhni padti hai, debugging ke liye. Jaise:
age = int(input("Apni age bata: "))
if age < 0:
raise ValueError("Negative age? Arey bro, possible nahi 😤")
else:
print("Age sahi hai 👍")
Mini Project: To-Do List App (File-Based) ✅
Chalo ab practical karte hain. Ek simple To-Do app banate hain jo tasks ko file me store kare. Matlab program close hone ke baad bhi sab safe rahe 💾
print("📝 Welcome to To-Do List App")
tasks = []
# Pehle se saved tasks load karo
try:
with open("tasks.txt", "r") as f:
tasks = [line.strip() for line in f.readlines()]
except FileNotFoundError:
open("tasks.txt", "w").close() # Empty file create kar diya
while True:
print("\n1. View Tasks")
print("2. Add Task")
print("3. Remove Task")
print("4. Exit")
choice = input("Enter choice: ")
if choice == "1":
if not tasks:
print("Koi task nahi bro 😎 Chill maar!")
else:
for i, task in enumerate(tasks, 1):
print(f"{i}. {task}")
elif choice == "2":
new_task = input("Naya task likh: ")
tasks.append(new_task)
with open("tasks.txt", "a") as f:
f.write(new_task + "\n")
print("Task add ho gaya ✅")
elif choice == "3":
remove_task = input("Kaunsa task remove karna hai? ")
if remove_task in tasks:
tasks.remove(remove_task)
with open("tasks.txt", "w") as f:
for t in tasks:
f.write(t + "\n")
print("Task remove ho gaya ✂️")
else:
print("Task mila nahi bro 😅")
elif choice == "4":
print("Saving and exiting... 👋")
break
else:
print("Bro, choice sahi se daal 😜")
Output example:
📝 Welcome to To-Do List App
1. View Tasks
2. Add Task
3. Remove Task
4. Exit
Enter choice: 2
Enter new task: Learn Python File Handling
Task add ho gaya ✅
Bro, ab data file me save ho gaya, next time open karoge toh sab safe 💾 Easy aur useful mini-project!
Bro-to-Bro Gyaan 💬
File handling aur error management Python ke real-world skills hain. Har app – game ho ya website ho – inpe depend karta hai. 😎
Error handling ek shield hai bro. Galti hoti hai sab se, par smart dev wo hai jo use gracefully handle kare 💪
Mujhe yaad hai pehli baar maine open("data.txt")
bina check ke likha tha – crash ho gaya pura program 😂 Tab samjha try-except ka asli maza.
Next Steps 🚀
- Ek notes app bana jo text save kare aur date/time add kare.
- JSON ke saath ek student record system banake dekho.
- Fir functions aur modules ki dunia me chalte hain (next blog 😉).
Tab tak bro – file handle kar, code likh, aur coffee pee ke chill maar ☕🐍
— Python + Coffee = Code 💻❤️
0 Comments