⚠ यह कार्रवाई अनुमति नहीं है!
🐍 NIELIT O Level · M3-R5 Python · Hindi Notes

Chapter 7: File Processing — Data को Permanently Save करना

Programs का data RAM में temporary रहता है — Files से हम उसे हमेशा के लिए save करते हैं! File Modes, read()/readline()/readlines(), write(), seek()/tell(), CSV Files, Pickling, Exception Handling व Command Line Arguments — सब diagrams के साथ।

📑 12 Sections 🖼️ 2 Diagrams 💻 40+ Examples ❓ 50 MCQs + Output Qs 🗓 Updated 2026
👉 सभी chapters देखने के लिए swipe करें
📑 Table of Contents — किसी भी topic पर सीधे जाएँ
7.0

File Handling क्यों? — RAM Temporary है, File Permanent

Program चलते समय data RAM में रहता है — program बंद, data गायब! File Handling से data storage (disk) पर हमेशा के लिए save होता है — program बंद होने के बाद भी data रहता है।

📁 Python में 3 प्रकार की Files

TypeExtensionक्या रहता है
Text Files.txtHuman-readable text (letters, digits)
Binary Files.jpg, .exe, .binNon-text data (images, videos)
CSV Files.csvTabular data (rows-columns, Excel जैसा)
🐍 सबसे पहला File Program▶ Run
f = open("demo.txt", "w")   # file kholi (write mode)
f.write("Hello Python!")    # likha
f.close()                   # band ki (zaroori!)
OUTPUTdemo.txt file बन गई जिसमें "Hello Python!" लिखा है।
Exam Point: RAM temporary, File permanent — यही file handling की मूल वजह है। open() → operations → close() — यह basic pattern सभी file work में लागू होता है।
7.1

File Modes — File से क्या करना है, बताना

Mode बताता है file के साथ क्या operation होगा — पढ़ना, लिखना, या जोड़ना। open("filename", "mode")

File Modes — कब क्या उपयोग करें

"r" ReadFile न मिले तो Error "w" Writeपुराना content DELETE! "a" Appendअंत में जोड़ता है "r+" Read+Writecontent सुरक्षित रहता "w+" Write+Readoverwrite भी करता है "a+" Append+Readजोड़ता व पढ़ता दोनों "rb" / "wb"Binary — images/videos newline=""CSV files के साथ ज़रूरी
🐍 r vs w — फ़र्क साफ़ देखिए▶ Run
# 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()
OUTPUTNaya data
← "Purana data" हमेशा के लिए गया, "w" mode overwrite करता है!
बड़ी सावधानी: "w" mode existing file का पूरा content मिटा देता है! अगर data बचाना है तो "a" (append) उपयोग करें।
Exam Point: r = read only (file न होने पर FileNotFoundError); w = overwrite/create; a = append (सुरक्षित जोड़); b = binary (images/videos)। CSV writing में newline="" न देने पर extra blank lines आती हैं।
7.2

Reading Functions — read(), readline(), readlines()

तीन तरीके file पढ़ने के — read() पूरा एक साथ, readline() एक-एक line, readlines() सभी lines की list। हमेशा best practice: with open() का उपयोग — close() अपने आप हो जाता है!
🐍 Setup — एक demo file बनाना▶ Run
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.")
🐍 read() — पूरी file एक string में▶ Run
with open("demo.txt", "r") as f:
    data = f.read()
    print(data)
OUTPUTPython is powerful.
File handling is easy.
Keep practicing daily.
🐍 readline() — एक-एक line▶ Run
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())
OUTPUTLine 1: Python is powerful.
Line 2: File handling is easy.
🐍 readlines() — सारी lines एक list में▶ Run
with open("demo.txt", "r") as f:
    lines = f.readlines()
    print(lines)
OUTPUT['Python is powerful.\n', 'File handling is easy.\n', 'Keep practicing daily.']
🐍 for loop — बड़ी files के लिए सबसे बेहतर तरीका▶ Run
with open("demo.txt", "r") as f:
    for line in f:
        print(line.strip())
OUTPUTPython is powerful.
File handling is easy.
Keep practicing daily.
Exam Point: read() → single string; readline() → एक line, हर call पर अगली line; readlines() → list of strings (हर string में \n शामिल)। बड़ी files में for line in file: memory-efficient है (सब एक साथ load नहीं होता)।
7.3

Writing Functions — write() व writelines()

write() एक string लिखता है; writelines() list/tuple of strings को एक साथ लिखता है (automatic newline नहीं जोड़ता — खुद \n लगाना पड़ता है)।
🐍 write() — एक-एक करके▶ Run
with open("info.txt", "w") as f:
    f.write("Welcome to Python!\n")
    f.write("Second line here.\n")
print("Likha gaya!")
OUTPUTLikha gaya!
🐍 writelines() — पूरी list एक साथ▶ Run
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!")
OUTPUTMultiple lines likhi gayi!

➕ Append Mode — पुराना सुरक्षित, नया जुड़े

🐍 append से data जोड़ना▶ Run
with open("info.txt", "a") as f:
    f.write("This line added later.\n")
print("Append ho gaya!")
OUTPUTAppend ho gaya!
Exam Point: write() = एक string; writelines() = list लिखता है (खुद \n जोड़ना पड़ता है, writelines automatic newline नहीं लगाती)। "w" = overwrite, "a" = safe जोड़ना।
7.4

seek() व tell() — File Pointer को Control करना

File खुलने पर एक pointer (cursor जैसा) शुरुआत (position 0) पर होता है — पढ़ते-लिखते ही आगे बढ़ता जाता है। tell() बताता है pointer कहाँ है; seek(n) उसे position n पर ले जाता है।

File Pointer — seek() व tell() का Movement

Hello ·World 01234 read(5) के बाद — pointer यहाँ (tell()=5) seek(0) — वापस शुरुआत में!
🐍 tell() व seek() Live देखिए▶ Run
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())  # 0
OUTPUTShuru me position: 0
Padha: Hello
5 chars ke baad position: 5
seek(0) ke baad position: 0
Exam Point: tell() = current byte position; seek(n) = pointer को position n पर ले जाना। seek(0) = फिर से शुरुआत से पढ़ने के लिए बहुत उपयोगी (जैसे "w+" mode में लिखने के बाद पढ़ना)।
7.5

CSV Files — Excel जैसा Tabular Data

CSV (Comma-Separated Values) rows-columns वाला data — csv module import करके handle करते हैं। newline="" लगाना ज़रूरी है, वरना Windows में extra blank lines आती हैं।
🐍 CSV में लिखना — csv.writer▶ Run
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!")
OUTPUTCSV ban gayi!
🐍 CSV पढ़ना — csv.reader▶ Run
import csv

with open("students.csv", "r") as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)
OUTPUT['Name', 'Age', 'Grade']
['Ravi', '20', 'A']
['Priya', '21', 'B']
🐍 DictReader — column headers को keys बनाना▶ Run
import csv

with open("students.csv", "r") as file:
    reader = csv.DictReader(file)
    for row in reader:
        print(dict(row))
OUTPUT{'Name': 'Ravi', 'Age': '20', 'Grade': 'A'}
{'Name': 'Priya', 'Age': '21', 'Grade': 'B'}
Exam Point: csv.writer().writerow() → single row लिखना; csv.reader() → हर row एक list के रूप में मिलता है; DictReader → हर row dictionary के रूप में (headers keys बनते हैं)। CSV write में हमेशा newline="" रखें।
7.6

Pickling व Unpickling — Python Objects को Save करना

List, dictionary जैसे पूरे Python objects को सीधे text में नहीं लिख सकते — pickle module उन्हें binary byte stream में बदल देता है। Pickling = save करना (dump); Unpickling = वापस लाना (load)।
🐍 Dictionary को Pickle करना व वापस लाना▶ Run
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)
OUTPUTPickled (save) ho gaya!
Unpickled: {'Name': 'Ravi', 'Age': 20, 'Marks': [85, 90, 88]}
Exam Point: pickle.dump(obj, file) → object को binary file में save; pickle.load(file) → वापस Python object में। दोनों के लिए mode "wb"/"rb" ज़रूरी (binary!)। Pickled data human-readable नहीं होता।
7.7

Exception Handling — File Errors से Program को बचाना

File न मिलना, permission न होना जैसी गलतियों से program crash न हो, इसके लिए try-except उपयोग करते हैं। File operations के साथ यह बहुत ज़रूरी है।
🐍 FileNotFoundError को Handle करना▶ Run
try:
    f = open("unknown.txt", "r")
    print(f.read())
except FileNotFoundError:
    print("Error: File maujood nahi hai.")
finally:
    print("Program complete hua.")
OUTPUTError: File maujood nahi hai.
Program complete hua.

⚠️ Common File Exceptions

Exceptionकब आती है
FileNotFoundErrorFile मौजूद नहीं है
PermissionErrorAccess permission नहीं है
IOErrorRead/Write में समस्या
IsADirectoryErrorPath एक file नहीं, folder है
Exam Point: try-except-finally block file errors से बचाता है; finally हमेशा चलता है (cleanup के लिए)। with open() अपने आप भी exception आने पर file close कर देता है।
7.8

Command Line Arguments — Terminal से Program को Input देना

Program को terminal से चलाते समय extra values pass करना — sys.argv list में सब values मिलती हैं। sys.argv[0] हमेशा file का नाम होता है।
🐍 sys.argv का उपयोग▶ Run
import sys
print("Sabhi arguments:", sys.argv)
print("Kul arguments:", len(sys.argv))
Terminal Command: python myfile.py hello worldSabhi arguments: ['myfile.py', 'hello', 'world']
Kul arguments: 3
🐍 Command Line से दो Numbers जोड़ना▶ Run
import sys
# command: python sum_args.py 12 8
a = int(sys.argv[1])
b = int(sys.argv[2])
print("Sum =", a + b)
OUTPUTSum = 20
Exam Point: sys.argv[0] = script का नाम; बाकी sys.argv[1], [2]... command line arguments (हमेशा string, int()/float() से convert करना पड़ता है)। len(sys.argv) से count पता चलता है।
7.9

🎯 Output-Based Questions — File Handling के Tricky सवाल

File modes, read functions, seek/tell के questions सबसे ज़्यादा confuse करते हैं — पहले खुद सोचिए!

Q1. "w" Mode का Overwrite Effect

🐍 क्या होगा file में?▶ Run
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())
ANSWERLine B
← "w" mode हर बार पुराना content मिटा देता है — "Line A" गायब हो गया!

Q2. readline() Sequential Behavior

🐍 Output बताइए (file में 3 lines हैं)▶ Run
# file: A\nB\nC
with open("f.txt", "r") as f:
    print(f.readline().strip())
    print(f.readline().strip())
ANSWERA
B
← हर readline() call अगली line देता है — पहला A, दूसरा B।

Q3. tell() का Position Tracking

🐍 Output बताइए▶ Run
with open("data.txt", "w") as f:
    f.write("ABCDEFGH")

with open("data.txt", "r") as f:
    f.read(3)
    print(f.tell())
ANSWER3
← 3 characters पढ़े गए, pointer position 3 पर पहुँच गया।

Q4. Append vs Write

🐍 अंतिम content क्या होगा?▶ Run
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())
ANSWERHello World
← "a" mode पुराना safe रखकर अंत में जोड़ता है।

Q5. File न मिलने पर Exception

🐍 Output बताइए▶ Run
try:
    f = open("nofile.txt", "r")
except FileNotFoundError:
    print("File nahi mili!")
else:
    print("File mil gayi")
ANSWERFile nahi mili!
← Error आने पर except चलता है, else तभी चलता जब कोई error न आए।

Q6. readlines() List Format

🐍 Output बताइए (file में 2 lines: X\nY)▶ Run
with open("f.txt", "r") as f:
    print(len(f.readlines()))
ANSWER2
← readlines() list में हर line एक element — यहाँ 2 lines, इसलिए list की length 2।

Q7. CSV Row Format

🐍 csv.reader से क्या मिलता है?▶ Run
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)
ANSWER<class 'list'> ['A', '1']
← csv.reader हर row को list of strings के रूप में देता है।

Q8. sys.argv Indexing

🐍 command: python test.py 5 10 — Output?▶ Run
import sys
print(sys.argv[0])
print(sys.argv[1])
ANSWERtest.py
5
← argv[0] हमेशा filename; argv[1] पहला दिया गया argument।
7.10

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 करना पड़ता है)।
7.11

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)

  1. File Handling की ज़रूरत क्यों पड़ती है?Program चलते समय data RAM (temporary memory) में रहता है — program बंद होते ही गायब। File handling से data को storage (disk) पर permanently save किया जाता है।
  2. Python में file के कितने प्रकार हैं? नाम लिखिए।3 प्रकार — Text files (.txt, human-readable), Binary files (.jpg/.exe, non-text data), CSV files (.csv, tabular rows-columns data)।
  3. r, w, a mode में अंतर बताइए।r = read only (file न मिले तो error); w = write, existing content delete करके नया लिखता है; a = append, existing content सुरक्षित रखते हुए अंत में जोड़ता है।
  4. read(), readline() और readlines() में अंतर लिखिए।read() पूरी file एक string में देता है; readline() हर call पर एक line देता है; readlines() सभी lines की list देता है।
  5. with open() क्यों उपयोग करना चाहिए?यह file को automatically close कर देता है — चाहे error आए या न आए, इसलिए यह manual open()/close() से ज़्यादा safe व clean है।
  6. seek() और tell() का काम समझाइए।tell() बताता है pointer अभी किस byte position पर है; seek(n) pointer को position n पर ले जाता है — seek(0) फिर से शुरुआत से पढ़ने के लिए उपयोगी है।
  7. CSV files के लिए किस module का उपयोग होता है? मुख्य functions लिखिए।csv module। Main functions — csv.writer().writerow() (लिखना), csv.reader() (पढ़ना, list में), csv.DictReader() (dictionary में, headers keys बनते हैं)।
  8. Pickling और Unpickling क्या हैं?Pickling — किसी Python object (list, dict) को byte stream में बदलकर binary file में save करना (pickle.dump)। Unpickling — उसे वापस Python object में convert करना (pickle.load)। दोनों के लिए wb/rb mode ज़रूरी।
  9. Exception handling file operations में क्यों ज़रूरी है?File न मिलना, permission न होना जैसी errors से program crash न हो — try-except-finally से इन्हें gracefully handle किया जाता है, program आगे बढ़ता रहता है।
  10. File handling में आने वाली 3 common exceptions लिखिए।FileNotFoundError (file मौजूद नहीं), PermissionError (access नहीं), IOError (read/write में समस्या)।
  11. Command Line Arguments क्या हैं? कैसे access करते हैं?Program को terminal से चलाते समय दी गई extra values — sys module import करके sys.argv list से access करते हैं। argv[0] filename, बाकी दी गई values (strings)।
  12. write() और writelines() में अंतर बताइए।write() एक string एक बार में लिखता है; writelines() list/tuple of strings को एक साथ लिखता है — दोनों में newline (\n) manually जोड़ना पड़ता है।
  13. 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 ज़रूरी है।
  14. DictReader व DictWriter का उपयोग समझाइए।DictReader — CSV row को dictionary के रूप में पढ़ता है (headers keys बनते हैं)। DictWriter — dictionary data को CSV rows में लिखता है, fieldnames से columns तय होते हैं।
  15. File न मिलने पर safe तरीके से handle करने का code लिखिए।try: with open(filename, "r") as f: print(f.read()) except FileNotFoundError: print("File not found") — इससे program crash नहीं होगा, user को साफ़ message मिलेगा।
Revision Tip: "w" mode का overwrite खतरा, read()/readline()/readlines() का अंतर, seek()/tell(), और FileNotFoundError handling — ये 4 areas हर exam में सबसे ज़्यादा पूछे जाते हैं। Section 7.9 के output questions ज़रूर दोहराएँ!
FAQ

अक्सर पूछे जाने वाले प्रश्न

Python में file modes कौन-कौन से हैं?
मुख्य modes — r (read, file न मिले तो error), w (write, पुराना content delete करके नया बनाता है), a (append, अंत में जोड़ता है), r+ (read+write), w+ (write+read, overwrite करता है), rb/wb (binary mode images-videos के लिए)।
read(), readline() और readlines() में क्या अंतर है?
read() पूरी file को एक string में देता है; readline() एक बार में एक line देता है; readlines() सभी lines की एक list देता है। बड़ी files के लिए for line in file: का उपयोग सबसे efficient है।
with open() का उपयोग क्यों करना चाहिए?
with open() automatically file को close कर देता है, चाहे कोई error आए या न आए — इसलिए यह manual open()/close() से ज़्यादा सुरक्षित है और resource leak नहीं होता।
Pickling और Unpickling क्या हैं?
Pickling किसी Python object (list, dict आदि) को byte stream में बदलकर binary file में save करना है (pickle.dump)। Unpickling उसे वापस Python object में convert करना है (pickle.load)। दोनों के लिए wb/rb mode ज़रूरी है।
seek() और tell() क्या करते हैं?
tell() बताता है कि file pointer अभी किस position पर है (byte number)। seek(n) pointer को position n पर ले जाता है — seek(0) फ़ाइल की शुरुआत में वापस ले जाता है।

🎯 Chapter 7 पूरा हुआ! अब आगे बढ़ें

Chapter 8 में Scope व Modules — variable scope की गहराई, अपना खुद का module बनाना व package structure।

Chapter 8 पढ़ें ➜