📑 Table of Contents — किसी भी topic पर सीधे जाएँ
File Handling क्यों? — RAM Temporary है, File Permanent
📁 Python में 3 प्रकार की Files
| Type | Extension | क्या रहता है |
|---|---|---|
| Text Files | .txt | Human-readable text (letters, digits) |
| Binary Files | .jpg, .exe, .bin | Non-text data (images, videos) |
| CSV Files | .csv | Tabular data (rows-columns, Excel जैसा) |
f = open("demo.txt", "w") # file kholi (write mode)
f.write("Hello Python!") # likha
f.close() # band ki (zaroori!)File Modes — File से क्या करना है, बताना
open("filename", "mode")File Modes — कब क्या उपयोग करें
# pehle likha
f = open("test.txt", "w")
f.write("Purana data")
f.close()
# ab dobara 'w' mode me kholna
f = open("test.txt", "w") # PURANA DATA DELETE HO GAYA!
f.write("Naya data")
f.close()
f = open("test.txt", "r")
print(f.read())
f.close()← "Purana data" हमेशा के लिए गया, "w" mode overwrite करता है!
Reading Functions — read(), readline(), readlines()
with open("demo.txt", "w") as f:
f.write("Python is powerful.\n")
f.write("File handling is easy.\n")
f.write("Keep practicing daily.")with open("demo.txt", "r") as f:
data = f.read()
print(data)File handling is easy.
Keep practicing daily.
with open("demo.txt", "r") as f:
line1 = f.readline()
line2 = f.readline()
print("Line 1:", line1.strip()) # strip() se \n hataya
print("Line 2:", line2.strip())Line 2: File handling is easy.
with open("demo.txt", "r") as f:
lines = f.readlines()
print(lines)with open("demo.txt", "r") as f:
for line in f:
print(line.strip())File handling is easy.
Keep practicing daily.
Writing Functions — write() व writelines()
with open("info.txt", "w") as f:
f.write("Welcome to Python!\n")
f.write("Second line here.\n")
print("Likha gaya!")lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
with open("notes.txt", "w") as f:
f.writelines(lines)
print("Multiple lines likhi gayi!")➕ Append Mode — पुराना सुरक्षित, नया जुड़े
with open("info.txt", "a") as f:
f.write("This line added later.\n")
print("Append ho gaya!")seek() व tell() — File Pointer को Control करना
File Pointer — seek() व tell() का Movement
with open("demo.txt", "w") as f:
f.write("Hello Python World!")
with open("demo.txt", "r") as f:
print("Shuru me position:", f.tell()) # 0
content = f.read(5)
print("Padha:", content) # Hello
print("5 chars ke baad position:", f.tell()) # 5
f.seek(0) # wapas shuru me
print("seek(0) ke baad position:", f.tell()) # 0Padha: Hello
5 chars ke baad position: 5
seek(0) ke baad position: 0
CSV Files — Excel जैसा Tabular Data
csv module import करके handle करते हैं। newline="" लगाना ज़रूरी है, वरना Windows में extra blank lines आती हैं।import csv
with open("students.csv", "w", newline="") as file:
writer = csv.writer(file)
writer.writerow(["Name", "Age", "Grade"])
writer.writerow(["Ravi", 20, "A"])
writer.writerow(["Priya", 21, "B"])
print("CSV ban gayi!")import csv
with open("students.csv", "r") as file:
reader = csv.reader(file)
for row in reader:
print(row)['Ravi', '20', 'A']
['Priya', '21', 'B']
import csv
with open("students.csv", "r") as file:
reader = csv.DictReader(file)
for row in reader:
print(dict(row)){'Name': 'Priya', 'Age': '21', 'Grade': 'B'}
Pickling व Unpickling — Python Objects को Save करना
import pickle
student = {"Name": "Ravi", "Age": 20, "Marks": [85, 90, 88]}
# Pickling (save)
with open("student.dat", "wb") as f:
pickle.dump(student, f)
print("Pickled (save) ho gaya!")
# Unpickling (load)
with open("student.dat", "rb") as f:
data = pickle.load(f)
print("Unpickled:", data)Unpickled: {'Name': 'Ravi', 'Age': 20, 'Marks': [85, 90, 88]}
Exception Handling — File Errors से Program को बचाना
try:
f = open("unknown.txt", "r")
print(f.read())
except FileNotFoundError:
print("Error: File maujood nahi hai.")
finally:
print("Program complete hua.")Program complete hua.
⚠️ Common File Exceptions
| Exception | कब आती है |
|---|---|
| FileNotFoundError | File मौजूद नहीं है |
| PermissionError | Access permission नहीं है |
| IOError | Read/Write में समस्या |
| IsADirectoryError | Path एक file नहीं, folder है |
Command Line Arguments — Terminal से Program को Input देना
sys.argv list में सब values मिलती हैं। sys.argv[0] हमेशा file का नाम होता है।import sys
print("Sabhi arguments:", sys.argv)
print("Kul arguments:", len(sys.argv))Kul arguments: 3
import sys
# command: python sum_args.py 12 8
a = int(sys.argv[1])
b = int(sys.argv[2])
print("Sum =", a + b)🎯 Output-Based Questions — File Handling के Tricky सवाल
Q1. "w" Mode का Overwrite Effect
with open("data.txt", "w") as f:
f.write("Line A")
with open("data.txt", "w") as f:
f.write("Line B")
with open("data.txt", "r") as f:
print(f.read())← "w" mode हर बार पुराना content मिटा देता है — "Line A" गायब हो गया!
Q2. readline() Sequential Behavior
# file: A\nB\nC
with open("f.txt", "r") as f:
print(f.readline().strip())
print(f.readline().strip())B
← हर readline() call अगली line देता है — पहला A, दूसरा B।
Q3. tell() का Position Tracking
with open("data.txt", "w") as f:
f.write("ABCDEFGH")
with open("data.txt", "r") as f:
f.read(3)
print(f.tell())← 3 characters पढ़े गए, pointer position 3 पर पहुँच गया।
Q4. Append vs Write
with open("f.txt", "w") as f:
f.write("Hello")
with open("f.txt", "a") as f:
f.write(" World")
with open("f.txt", "r") as f:
print(f.read())← "a" mode पुराना safe रखकर अंत में जोड़ता है।
Q5. File न मिलने पर Exception
try:
f = open("nofile.txt", "r")
except FileNotFoundError:
print("File nahi mili!")
else:
print("File mil gayi")← Error आने पर except चलता है, else तभी चलता जब कोई error न आए।
Q6. readlines() List Format
with open("f.txt", "r") as f:
print(len(f.readlines()))← readlines() list में हर line एक element — यहाँ 2 lines, इसलिए list की length 2।
Q7. CSV Row Format
import csv
with open("data.csv", "w", newline="") as f:
csv.writer(f).writerow(["A", "1"])
with open("data.csv", "r") as f:
for row in csv.reader(f):
print(type(row), row)← csv.reader हर row को list of strings के रूप में देता है।
Q8. sys.argv Indexing
import sys print(sys.argv[0]) print(sys.argv[1])
5
← argv[0] हमेशा filename; argv[1] पहला दिया गया argument।
Summary — Quick Revision (Exam से पहले पढ़ें)
- File types: Text (.txt), Binary (.jpg/.exe), CSV (.csv — tabular)। RAM temporary, File permanent।
- Modes: r (read, error if missing), w (write, overwrite!), a (append, safe जोड़ना), r+/w+/a+ combined, rb/wb binary।
- Reading: read() पूरी string; readline() एक line; readlines() list of lines; for line in file: सबसे efficient।
- Writing: write() एक string; writelines() list — दोनों में \n खुद जोड़ना पड़ता है।
- with open() — file automatic close, error आने पर भी — यही best practice है।
- tell() current pointer position बताता है; seek(n) pointer को position n पर ले जाता है।
- CSV: csv.writer().writerow() से लिखना; csv.reader() list देता है; DictReader dictionary देता है (headers keys)।
- Pickling = Python object को binary file में save (pickle.dump); Unpickling = वापस लाना (pickle.load); mode wb/rb ज़रूरी।
- Exception handling: try-except-finally से FileNotFoundError, PermissionError, IOError को handle करना।
- Command Line Arguments: sys.argv list — argv[0] filename, argv[1:] दी गई values (हमेशा strings, convert करना पड़ता है)।
Model Questions — 50 MCQs + 15 Theory Questions
❓ A. Multiple Choice Questions (50)
| # | प्रश्न |
|---|---|
| 1 | File खोलने के लिए function है — (a) file()(b) open()(c) start()(d) access() ✔ सही उत्तर: (b) open()open("filename", "mode") syntax। |
| 2 | Read mode कौन-सा symbol है? (a) w(b) a(c) r(d) x ✔ सही उत्तर: (c) rFile न मिलने पर FileNotFoundError देता है। |
| 3 | "w" mode existing file के साथ क्या करता है? (a) सुरक्षित रखता है(b) पूरा content delete कर देता है(c) सिर्फ पढ़ता है(d) कुछ नहीं ✔ सही उत्तर: (b) पूरा content delete कर देता हैOverwrite होता है। |
| 4 | पुराने data को सुरक्षित रखते हुए नया जोड़ने वाला mode — (a) w(b) r(c) a(d) x ✔ सही उत्तर: (c) aAppend mode अंत में जोड़ता है। |
| 5 | Binary files के लिए mode में जोड़ते हैं — (a) x(b) t(c) b(d) y ✔ सही उत्तर: (c) brb, wb जैसे — images/videos के लिए। |
| 6 | पूरी file एक string में देने वाला function — (a) readline()(b) readlines()(c) read()(d) load() ✔ सही उत्तर: (c) read()पूरा content एक साथ। |
| 7 | एक बार में एक line पढ़ने वाला function — (a) read()(b) readline()(c) readlines()(d) getline() ✔ सही उत्तर: (b) readline()हर call पर अगली line। |
| 8 | सभी lines की list देने वाला function — (a) read()(b) readline()(c) readlines()(d) getlines() ✔ सही उत्तर: (c) readlines()List of strings, हर एक में \n शामिल। |
| 9 | एक string file में लिखने वाला function — (a) write()(b) writelines()(c) put()(d) save() ✔ सही उत्तर: (a) write()Single string लिखता है। |
| 10 | List of strings एक साथ लिखने वाला function — (a) write()(b) writelines()(c) writeall()(d) print() ✔ सही उत्तर: (b) writelines()List/tuple accept करता है। |
| 11 | writelines() automatic newline — (a) जोड़ता है(b) नहीं जोड़ता — खुद \n लगाना पड़ता है(c) हमेशा हटा देता है(d) दो बार जोड़ता है ✔ सही उत्तर: (b) नहीं जोड़ताList के हर string में manually \n रखना पड़ता है। |
| 12 | File को automatic close करने वाला statement — (a) auto open()(b) with open()(c) safe open()(d) close open() ✔ सही उत्तर: (b) with open()Block खत्म होते ही file close, error आने पर भी। |
| 13 | File pointer की position बताने वाला function — (a) position()(b) tell()(c) locate()(d) point() ✔ सही उत्तर: (b) tell()Byte number return करता है। |
| 14 | File pointer को move करने वाला function — (a) move()(b) go()(c) seek()(d) jump() ✔ सही उत्तर: (c) seek()seek(n) से position n पर जाना। |
| 15 | seek(0) क्या करता है? (a) File बंद करता है(b) Pointer को शुरुआत में ले जाता है(c) File delete करता है(d) कुछ नहीं ✔ सही उत्तर: (b) Pointer को शुरुआत में ले जाता हैPosition 0 पर वापस। |
| 16 | CSV files handle करने के लिए module — (a) file(b) csv(c) table(d) excel ✔ सही उत्तर: (b) csvimport csv के बाद उपयोग। |
| 17 | CSV में एक row लिखने का method — (a) write()(b) writerow()(c) addrow()(d) insert() ✔ सही उत्तर: (b) writerow()csv.writer(file).writerow([...])। |
| 18 | CSV row headers को dictionary keys बनाने वाला class — (a) csv.reader(b) csv.DictReader(c) csv.writer(d) csv.KeyReader ✔ सही उत्तर: (b) csv.DictReaderपहली row headers, बाकी values। |
| 19 | CSV writing में newline="" क्यों दिया जाता है? (a) Speed बढ़ाने के लिए(b) Extra blank lines रोकने के लिए(c) File छोटी करने के लिए(d) ज़रूरी नहीं है ✔ सही उत्तर: (b) Extra blank lines रोकने के लिएखासकर Windows पर। |
| 20 | csv.reader() हर row किस रूप में देता है? (a) String(b) List(c) Dictionary(d) Tuple ✔ सही उत्तर: (b) ListList of string values। |
| 21 | Python object को binary file में save करना कहलाता है — (a) Encoding(b) Pickling(c) Compiling(d) Serializing text ✔ सही उत्तर: (b) Picklingpickle.dump() से। |
| 22 | Binary file से Python object वापस लाना कहलाता है — (a) Decoding(b) Unpickling(c) Reading(d) Extracting ✔ सही उत्तर: (b) Unpicklingpickle.load() से। |
| 23 | Pickling के लिए कौन-सा module चाहिए? (a) csv(b) json(c) pickle(d) os ✔ सही उत्तर: (c) pickleimport pickle। |
| 24 | pickle.dump() के लिए कौन-सा mode चाहिए? (a) "r"(b) "w"(c) "wb"(d) "a" ✔ सही उत्तर: (c) "wb"Binary write mode ज़रूरी है। |
| 25 | Pickled data human-readable होता है क्या? (a) हाँ(b) नहीं(c) कभी-कभी(d) सिर्फ numbers के लिए ✔ सही उत्तर: (b) नहींBinary format में stored। |
| 26 | File न मिलने पर आने वाली exception — (a) ValueError(b) FileNotFoundError(c) TypeError(d) IndexError ✔ सही उत्तर: (b) FileNotFoundErrorRead mode में file exist न होने पर। |
| 27 | try-except में हमेशा execute होने वाला block — (a) else(b) except(c) finally(d) try ✔ सही उत्तर: (c) finallyError आए या न आए, यह हमेशा चलता है। |
| 28 | else block try-except में कब चलता है? (a) हमेशा(b) Error आने पर(c) कोई error न आने पर(d) कभी नहीं ✔ सही उत्तर: (c) कोई error न आने परtry सफल हो तभी else चलता है। |
| 29 | Permission न होने पर आने वाली exception — (a) IOError(b) PermissionError(c) ValueError(d) KeyError ✔ सही उत्तर: (b) PermissionErrorAccess denied होने पर। |
| 30 | with open() और try-except में safer कौन? (a) दोनों बराबर सुरक्षित(b) with open() अकेला काफी नहीं, दोनों साथ बेहतर(c) सिर्फ try-except(d) कोई ज़रूरी नहीं ✔ सही उत्तर: (b) दोनों साथ बेहतरwith से close automatic, try-except से errors handle। |
| 31 | Command line arguments access करने के लिए module — (a) os(b) sys(c) csv(d) argparse only ✔ सही उत्तर: (b) syssys.argv list देता है। |
| 32 | sys.argv[0] में क्या होता है? (a) पहला argument(b) Script का नाम(c) खाली string(d) Error ✔ सही उत्तर: (b) Script का नामहमेशा 0th index पर filename। |
| 33 | python test.py 5 10 में len(sys.argv) — (a) 2(b) 3(c) 4(d) 1 ✔ सही उत्तर: (b) 3['test.py', '5', '10'] — 3 elements। |
| 34 | Command line arguments किस data type में आते हैं? (a) int(b) float(c) string(d) list of int ✔ सही उत्तर: (c) stringNumbers चाहिए तो int()/float() convert करना पड़ता है। |
| 35 | File open करके close न करने से क्या समस्या होती है? (a) कुछ नहीं(b) Memory/resource leak हो सकती है(c) Program तेज़ होता है(d) File corrupt हो जाती है हमेशा ✔ सही उत्तर: (b) Memory/resource leak हो सकती हैइसीलिए close() या with open() ज़रूरी। |
| 36 | File object का closed attribute क्या बताता है? (a) File का size(b) File बंद है या नहीं (True/False)(c) File का नाम(d) File का mode ✔ सही उत्तर: (b) File बंद है या नहींf.closed — True/False। |
| 37 | os.path.exists() क्या check करता है? (a) File खुली है या नहीं(b) File मौजूद है या नहीं(c) File का size(d) File का mode ✔ सही उत्तर: (b) File मौजूद है या नहींFileNotFoundError से पहले check करने के लिए। |
| 38 | os.remove() क्या करता है? (a) File बनाता है(b) File delete करता है(c) File rename करता है(d) File copy करता है ✔ सही उत्तर: (b) File delete करता हैos module का function। |
| 39 | os.rename(old, new) क्या करता है? (a) File delete(b) File का नाम बदलता है(c) File copy करता है(d) File size बताता है ✔ सही उत्तर: (b) File का नाम बदलता है |
| 40 | Text file और Binary file में मुख्य अंतर — (a) Size(b) Text = human-readable, Binary = raw bytes(c) कोई अंतर नहीं(d) Extension ही अंतर है ✔ सही उत्तर: (b) Text = human-readable, Binary = raw bytes |
| 41 | "r+" mode में क्या होता है? (a) सिर्फ पढ़ सकते हैं(b) पढ़ व लिख दोनों, पुराना content सुरक्षित(c) पुराना content delete होता है(d) सिर्फ लिख सकते हैं ✔ सही उत्तर: (b) पढ़ व लिख दोनों, पुराना content सुरक्षित |
| 42 | "w+" mode में क्या होता है? (a) पुराना content सुरक्षित रहता है(b) पुराना content delete होकर पढ़-लिख दोनों(c) सिर्फ append करता है(d) Error देता है ✔ सही उत्तर: (b) पुराना content delete होकर पढ़-लिख दोनों"r+" से यही मुख्य अंतर है। |
| 43 | DictWriter class का काम — (a) Dictionary को CSV rows में लिखना(b) CSV को dictionary में पढ़ना(c) File delete करना(d) Pickle करना ✔ सही उत्तर: (a) Dictionary को CSV rows में लिखनाfieldnames व writerow(s) से। |
| 44 | एक pickle file में कितने objects रख सकते हैं? (a) सिर्फ 1(b) कई (multiple dump calls से)(c) सिर्फ 2(d) कोई नहीं ✔ सही उत्तर: (b) कईहर dump() एक object जोड़ता है, load() उसी क्रम में मिलता है। |
| 45 | for line in file: का फायदा बड़ी files के लिए — (a) Memory-efficient (सब एक साथ load नहीं)(b) Slower होता है(c) Error देता है(d) कोई फायदा नहीं ✔ सही उत्तर: (a) Memory-efficientreadlines() पूरी file memory में लोड करता है, यह नहीं। |
| 46 | strip() का उपयोग file reading में क्यों होता है? (a) File delete करने के लिए(b) \n जैसे extra whitespace हटाने के लिए(c) Encoding बदलने के लिए(d) File खोलने के लिए ✔ सही उत्तर: (b) \n जैसे extra whitespace हटाने के लिएreadline() से मिली line में \n रहता है। |
| 47 | IOError किस स्थिति में आता है? (a) Wrong syntax पर(b) Read/Write operation में समस्या पर(c) Loop में गलती पर(d) Variable न मिलने पर ✔ सही उत्तर: (b) Read/Write operation में समस्या पर |
| 48 | File की size जानने के लिए os function — (a) os.size()(b) os.stat()(c) os.length()(d) os.info() ✔ सही उत्तर: (b) os.stat()st_size attribute से bytes में size मिलती है। |
| 49 | CSV, Text व Binary में से कौन Excel जैसा tabular data रखता है? (a) Text(b) Binary(c) CSV(d) कोई नहीं ✔ सही उत्तर: (c) CSVRows-columns में structured data। |
| 50 | File handling की सबसे बड़ी उपयोगिता — (a) Program को तेज़ बनाना(b) Data को permanently save करना(c) Memory खाली करना(d) Syntax कम करना ✔ सही उत्तर: (b) Data को permanently save करनाRAM temporary है, file permanent। |
📝 B. 15 Theory Questions (Short Answers)
- File Handling की ज़रूरत क्यों पड़ती है?Program चलते समय data RAM (temporary memory) में रहता है — program बंद होते ही गायब। File handling से data को storage (disk) पर permanently save किया जाता है।
- Python में file के कितने प्रकार हैं? नाम लिखिए।3 प्रकार — Text files (.txt, human-readable), Binary files (.jpg/.exe, non-text data), CSV files (.csv, tabular rows-columns data)।
- r, w, a mode में अंतर बताइए।r = read only (file न मिले तो error); w = write, existing content delete करके नया लिखता है; a = append, existing content सुरक्षित रखते हुए अंत में जोड़ता है।
- read(), readline() और readlines() में अंतर लिखिए।read() पूरी file एक string में देता है; readline() हर call पर एक line देता है; readlines() सभी lines की list देता है।
- with open() क्यों उपयोग करना चाहिए?यह file को automatically close कर देता है — चाहे error आए या न आए, इसलिए यह manual open()/close() से ज़्यादा safe व clean है।
- seek() और tell() का काम समझाइए।tell() बताता है pointer अभी किस byte position पर है; seek(n) pointer को position n पर ले जाता है — seek(0) फिर से शुरुआत से पढ़ने के लिए उपयोगी है।
- CSV files के लिए किस module का उपयोग होता है? मुख्य functions लिखिए।csv module। Main functions — csv.writer().writerow() (लिखना), csv.reader() (पढ़ना, list में), csv.DictReader() (dictionary में, headers keys बनते हैं)।
- Pickling और Unpickling क्या हैं?Pickling — किसी Python object (list, dict) को byte stream में बदलकर binary file में save करना (pickle.dump)। Unpickling — उसे वापस Python object में convert करना (pickle.load)। दोनों के लिए wb/rb mode ज़रूरी।
- Exception handling file operations में क्यों ज़रूरी है?File न मिलना, permission न होना जैसी errors से program crash न हो — try-except-finally से इन्हें gracefully handle किया जाता है, program आगे बढ़ता रहता है।
- File handling में आने वाली 3 common exceptions लिखिए।FileNotFoundError (file मौजूद नहीं), PermissionError (access नहीं), IOError (read/write में समस्या)।
- Command Line Arguments क्या हैं? कैसे access करते हैं?Program को terminal से चलाते समय दी गई extra values — sys module import करके sys.argv list से access करते हैं। argv[0] filename, बाकी दी गई values (strings)।
- write() और writelines() में अंतर बताइए।write() एक string एक बार में लिखता है; writelines() list/tuple of strings को एक साथ लिखता है — दोनों में newline (\n) manually जोड़ना पड़ता है।
- Binary file व Text file को handle करने में क्या अंतर है?Text files "r"/"w" mode (string data) से; Binary files "rb"/"wb" mode (bytes data) से — images/videos जैसी non-text files के लिए binary mode ज़रूरी है।
- DictReader व DictWriter का उपयोग समझाइए।DictReader — CSV row को dictionary के रूप में पढ़ता है (headers keys बनते हैं)। DictWriter — dictionary data को CSV rows में लिखता है, fieldnames से columns तय होते हैं।
- File न मिलने पर safe तरीके से handle करने का code लिखिए।try: with open(filename, "r") as f: print(f.read()) except FileNotFoundError: print("File not found") — इससे program crash नहीं होगा, user को साफ़ message मिलेगा।