📁 Unit 1 – File Handling · Lesson 07
pickle के साथ Binary Files
Binary file क्या है?
Binary file data को raw bytes के रूप में उसी तरह रखती है जैसे computer memory में use करता है, पढ़ने लायक characters के रूप में नहीं। Notepad में खोलने पर अजीब symbols दिखते हैं। Binary files compact होती हैं और पूरे Python objects — lists, dictionaries, tuples — जैसे के तैसे रख सकती हैं।
Pickling और unpickling
pickle.dump() और pickle.load()
Syntax
import pickle pickle.dump(object, file_object) # file opened in 'wb' or 'ab' object = pickle.load(file_object) # file opened in 'rb'
Python
import pickle
data = {'roll': 1, 'name': 'Asha', 'marks': 91.5}
with open('one.dat', 'wb') as f: # 'wb' = write binary
pickle.dump(data, f) # serialise (pickle) the object
with open('one.dat', 'rb') as f: # 'rb' = read binary
back = pickle.load(f) # deserialise (unpickle)
print(back, type(back)){'roll': 1, 'name': 'Asha', 'marks': 91.5} <class 'dict'>
कई records लिखना
Python
import pickle
def write_records():
students = [[1, 'Asha', 91.5], [2, 'Ravi', 72.0], [3, 'Neha', 85.0], [4, 'Kabir', 64.5]]
with open('student.dat', 'wb') as f:
for rec in students:
pickle.dump(rec, f) # one dump per record
print(len(students), 'records written')
write_records()4 records written
EOFError तक पढ़ना
Python
import pickle
def read_all():
with open('student.dat', 'rb') as f:
while True:
try:
rec = pickle.load(f)
print(rec)
except EOFError: # end of file reached
break
read_all()[1, 'Asha', 91.5]
[2, 'Ravi', 72.0]
[3, 'Neha', 85.0]
[4, 'Kabir', 64.5]
while True … except EOFError: break pattern हर record पढ़ने का standard board answer है।
Search और count
Python
import pickle
def search(roll):
found = False
with open('student.dat', 'rb') as f:
try:
while True:
rec = pickle.load(f)
if rec[0] == roll:
print('Found:', rec)
found = True
except EOFError:
pass
if not found:
print('Roll', roll, 'not found')
search(3)
search(9)Found: [3, 'Neha', 85.0]
Roll 9 not found
Python
import pickle
def count_above(limit):
n = 0
with open('student.dat', 'rb') as f:
try:
while True:
if pickle.load(f)[2] > limit:
n += 1
except EOFError:
pass
return n
print('Students above 80:', count_above(80))Students above 80: 2
Records append करना
Python
import pickle
def append_record(rec):
with open('student.dat', 'ab') as f: # 'ab' keeps old records
pickle.dump(rec, f)
append_record([5, 'Meher', 88.0])
with open('student.dat', 'rb') as f:
recs = []
try:
while True:
recs.append(pickle.load(f))
except EOFError:
pass
print(len(recs), 'records; last =', recs[-1])5 records; last = [5, 'Meher', 88.0]
Record update करना
- 1
rbमें खोलकर सारे records list में load करें। - 2Record ढूँढकर list में बदलें।
- 3
wbमें खोलकर हर record फिर से dump करें।
Python
import pickle
def update_marks(roll, new_marks):
recs = []
with open('student.dat', 'rb') as f: # 1. read all records
try:
while True:
recs.append(pickle.load(f))
except EOFError:
pass
for r in recs: # 2. change in memory
if r[0] == roll:
r[2] = new_marks
with open('student.dat', 'wb') as f: # 3. write all back
for r in recs:
pickle.dump(r, f)
update_marks(2, 78.0)
with open('student.dat', 'rb') as f:
pickle.load(f)
print(pickle.load(f)) # second record[2, 'Ravi', 78.0]
Record delete करना
Python
import pickle
def delete_record(roll):
keep = []
with open('student.dat', 'rb') as f:
try:
while True:
r = pickle.load(f)
if r[0] != roll:
keep.append(r)
except EOFError:
pass
with open('student.dat', 'wb') as f:
for r in keep:
pickle.dump(r, f)
print('Remaining rolls:', [r[0] for r in keep])
delete_record(4)Remaining rolls: [1, 2, 3, 5]
पूरा collection dump करना
Python
import pickle
# A whole list or dictionary can also be dumped in ONE go
book = {'B1': ('Python', 450), 'B2': ('SQL', 380)}
with open('books.dat', 'wb') as f:
pickle.dump(book, f)
with open('books.dat', 'rb') as f:
b = pickle.load(f)
for code, (title, price) in b.items():
print(code, title, price)B1 Python 450
B2 SQL 380
Binary files में tell() और seek()
Python
import pickle
with open('student.dat', 'rb') as f:
pickle.load(f)
pos = f.tell() # byte position after the first record
second = pickle.load(f)
f.seek(pos) # go back and read the same record again
print(second == pickle.load(f), pos > 0)True True
Text vs binary files
Text file
- Characters रखती है; Notepad में पढ़ सकते हैं
- हर line \n (EOL) पर ख़त्म
- Modes r, w, a
- बड़े structured data के लिए धीमी
Binary file
- Bytes रखती है; पढ़ने लायक नहीं
- कोई line structure नहीं
- Modes rb, wb, ab, rb+
- तेज़; pickle से Python objects रखती है
सारांश और practice
- Binary files bytes रखती हैं; rb / wb / ab से खोलें।
- pickle.dump(obj, f) लिखता है; pickle.load(f) एक object पढ़ता है; EOFError अंत बताता है।
- Load loop से search/count; सब पढ़कर, बदलकर, दोबारा लिखकर update/delete।
✅ Board-style question
Binary file EMP.DAT में records [EmpID, Name, Salary] हैं। def CountHigh(): लिखें जो 50000 से ज़्यादा salary वाले employees दिखाए और गिने।
अक्सर पूछे जाने वाले प्रश्न (FAQ)
Pickling क्या है?
Python object (list, dictionary, tuple…) को bytes की stream में बदलना ताकि वह binary file में store हो सके। Unpickling bytes को वापस same object में बदलता है।
Binary file पढ़ते समय EOFError क्यों पकड़ते हैं?
आमतौर पर हमें पता नहीं होता file में कितने records हैं। पढ़ने को कुछ न बचे तो pickle.load() EOFError देता है, इसलिए उसे पकड़ना loop रोकने का संकेत है।
Binary file में record update कैसे होता है?
सारे records list में पढ़ें, memory में ज़रूरी record बदलें, फिर पूरी list mode "wb" से वापस लिखें। (Advanced: size बराबर हो तो tell() और seek() से उसी जगह overwrite।)
