🟢 Beginner · Lesson 19
Python में File Handling
File Handling क्या है?
File handling program को data file में save करके बाद में वापस पढ़ने देता है — ताकि program खत्म होने पर data खो न जाए। असली apps इसी तरह notes, records और reports store करते हैं।
File Modes
| Mode | मतलब |
|---|---|
| "r" | Read (file होनी चाहिए) |
| "w" | Write (नई बनाता / पुरानी मिटाता) |
| "a" | Append (अंत में जोड़ता) |
| "r+" | Read और write |
Open, Read, Close
मूल flow: file open() करें, काम करें, फिर close() करें। और बेहतर, with use करें जो अपने आप close करता है।
Program 1: File में Write करें
Python – write.py
f = open("notes.txt", "w")
f.write("Hello from Python\n")
f.write("This is line 2\n")
f.close()
print("File written successfully")File written successfully
"w"notes.txtबनाता है (या मौजूद हो तो मिटा देता है)।\nनई line पर ले जाता है;.close()file save करता है।
Program 2: File Read करें
Python – read.py
f = open("notes.txt", "r")
content = f.read()
f.close()
print(content)Hello from Python
This is line 2
.read() पूरी file को एक string के रूप में लौटाता है।
Program 3: Data Append करें
Python – append.py
f = open("notes.txt", "a")
f.write("This line was added later\n")
f.close()
print("Line appended")Line appended
"a" पुराना content रखकर नई line अंत में जोड़ता है ("w" के उलट जो मिटा देता है)।
Program 4: `with` से Line by Line Read
Python – withread.py
with open("notes.txt", "r") as f:
for line in f:
print(line.strip())
# file यहाँ अपने आप close होती हैHello from Python
This is line 2
This line was added later
withfile अपने आप close करता है — error होने पर भी।fपर loop एक बार में एक line पढ़ता है (memory-friendly)।.strip()extra newline हटाता है।
सामान्य गलतियाँ
"a"की जगह"w"use करना — यह file मिटा देता है!- file close करना भूलना (सुरक्षित रहने को
withuse करें)। - न मौजूद file को
"r"mode में खोलना → FileNotFoundError।
Practice Tasks
- 5 student names file में लिखें, हर एक नई line पर।
- File पढ़कर गिनें कि उसमें कितनी lines हैं।
- हर बार program चलने पर log file में आज की date append करें।
- File पढ़कर उसे UPPERCASE में print करें।
सारांश
- File handling data को स्थायी रूप से save और read करता है।
- Modes:
"r"read,"w"write/erase,"a"append। with open(...) as f:use करें — यह file अपने आप close करता है।
अक्सर पूछे जाने वाले प्रश्न (FAQ)
with open(...) क्यों इस्तेमाल करें?
with statement error आने पर भी file अपने-आप बंद करता है, जिससे data save होता है और file lock नहीं रहती।
"w" और "a" mode में क्या अंतर है?
"w" नई file बनाता है या पुराना content मिटा देता है; "a" file के अंत में नया data जोड़ता है।
File से Hindi text सही तरीके से कैसे पढ़ें?
UTF-8 encoding से खोलें: open("notes.txt", encoding="utf-8")।
💻 लाइव कोड एडिटर
इस पेज के प्रोग्राम यहीं तैयार हैं — चलाएँ, बदलें और सीखें। कुछ भी इंस्टॉल किए बिना।
OneCompiler द्वारा संचालित। कोड एडिटर में अपने आप आ जाता है — Run दबाकर आउटपुट देखें। अगर एडिटर न खुले तो नए टैब में खोलें.
