Lesson 24 � Foundation

FILE HANDLING:
DATA PERMANENTLY STORE KARNA.

Programs run hone ke baad variables aur data gayab ho jaate hain. File handling se aap data ko permanent store kar sakte ho � text, CSV, JSON sab files mein save hota hai. Ye lesson sikhaega ki Python se files kaise read, write aur manage karte hain.

? 22 min✓ IntermediatePrerequisite: OOP Advanced

WHY: File handling kyun zaroori hai?

Socho aap ek app bana rahe ho jisme users apne notes save karna chahte hain. Agar aap sirf variables mein data rakho toh program band hone ke baad sab data gayab ho jaayega. File handling se data ko hard disk par permanently save kiya ja sakta hai. CSV, TXT, JSON � ye sab files hain jo hum daily use karte hain.

READ

open() se file padhna � data access karna aur process karna.

WRITE

File mein data likhna � naya content create ya update karna.

CONTEXT

with statement se file automatically close hoti hai � safe aur clean.

CSV

Comma-separated values format � data exchange ka sabse popular format.

WHEN: kab use hota hai

File handling tab use hota hai jab aapko data permanently store karna ho � user notes save karna, reports generate karna, data import/export karna, configuration files read karna, ya log files maintain karna. Har data-driven application file handling use karti hai.

HOW: file operations

File likhna (write)

python
# Write file
with open("notes.txt", "w") as f:
 f.write("Python seekh raha hoon\n")
 f.write("Line 2\n")

"w" mode se file open hoti hai write ke liye. Agar file nahi hai toh ban jaati hai. Agar hai toh purana content overwrite ho jaata hai. with statement ensure karta hai ki file automatically close ho jaaye.

File padhna (read)

python
# Read file
with open("notes.txt", "r") as f:
 content = f.read()
 print(content)

"r" mode se file padhte hain. f.read() poori file ka content ek string mein return karta hai. File exist nahi karegi toh error aayega.

Line by line padhna

python
# Read line by line
with open("notes.txt", "r") as f:
 for line in f:
 print(line.strip())

File ko directly loop mein iterate kar sakte ho � har iteration mein ek line milta hai. strip() se newline characters remove hote hain.

CSV file handling

python
import csv

# CSV file likhna
with open("students.csv", "w", newline="") as f:
 writer = csv.writer(f)
 writer.writerow(["Name", "Marks"])
 writer.writerow(["Aman", 85])
 writer.writerow(["Priya", 92])

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

csv module se CSV files handle karna easy hota hai. writerow() se ek row write hoti hai, csv.reader() se har row ek list ke rothi hai. newline="" Windows par extra blank lines prevent karta hai.

Try it: Simple Notes AppFile mein notes likho aur padho
Code ko apni values se update karke run karein

File modes explained

python
# "r" - Read mode (default) - sirf padhna
# "w" - Write mode - likhna (purana data delete)
# "a" - Append mode - end mein data add karna
# "r+" - Read + Write - dono kar sakte ho

# Append mode example
with open("notes.txt", "a") as f:
 f.write("Ye line append hui hai\n")

# Read + Write mode
with open("notes.txt", "r+") as f:
 content = f.read()
 print("Existing:", content[:20])
 f.write("Aur kuch likh diya")

"a" mode mein purana data safe rehta hai � nayi line sirf end mein add hoti hai. "r+" se file padh bhi sakte ho aur likh bhi sakte ho.

Useful file methods

Context manager: with statement

python
# WITHOUT with - manual close karna padta hai
f = open("test.txt", "w")
f.write("Hello")
f.close() # bhool gaye toh problem

# WITH - automatic close hota hai
with open("test.txt", "w") as f:
 f.write("Hello")
# yahan tak aate hi file automatically close ho jaati hai

# Multiple files ek saath
with open("input.txt", "r") as fin, open("output.txt", "w") as fout:
 for line in fin:
 fout.write(line.upper())

with statement use karna best practice hai � file hamesha close hoti hai chahe error aaye ya na aaye. Multiple files ko ek with mein open kar sakte ho.

CSV module deep dive

python
import csv

# Dictionary writer se CSV
with open("marks.csv", "w", newline="") as f:
 fields = ["Name", "Math", "Science", "English"]
 writer = csv.DictWriter(f, fieldnames=fields)
 writer.writeheader()
 writer.writerow({"Name": "Aman", "Math": 85, "Science": 90, "English": 78})
 writer.writerow({"Name": "Priya", "Math": 92, "Science": 88, "English": 95})

# Dictionary reader se padhna
with open("marks.csv", "r") as f:
 reader = csv.DictReader(f)
 for row in reader:
 print(f"{row['Name']}: Math={row['Math']}, Science={row['Science']}")

DictWriter aur DictReader se dictionary-based data handle hota hai � column names ke through access milta hai jo zyada readable hai.

Quick check

File write karo jo "Hello Python" text contain kare.

Pehle with open("test.txt", "w") as f: likho, phir f.write() se text likho.

Common mistakes

File handling clear?

Ab aap files read, write aur manage kar sakte ho � ye skill har Python project mein kaam aayegi.