Free tutorials & notes in Hindi & English · Clean code examples 🧰 मुफ़्त PDF और फ़ोटो टूल्स →
📁 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

['Asha', 91.5]Python objectpickle.dump()pickling (serialise)0x80 0x04 …student.dat में bytespickle.load()unpickling['Asha', 91.5]वही object वापस
pickle module objects ↔ bytes बदलता है

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. 1rb में खोलकर सारे records list में load करें।
  2. 2Record ढूँढकर list में बदलें।
  3. 3wb में खोलकर हर record फिर से dump करें।
Read – modify – write back
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 रखती है
Text vs binary

सारांश और 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।)
← Class 12 Computer Science
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

अगला topicCSV Files: reader और writer आपकी प्रगति: 7 / 26 (27%) · Lesson 8 / 26 आगे बढ़ें →

यह lesson कैसा लगा?

आपकी राय से हम content और बेहतर बनाते हैं।

अपना review और सुझाव लिखें (वैकल्पिक)

Review approve होने के बाद आपका नाम और शहर इसके साथ public दिख सकते हैं। Email या phone न लिखें।

▶ CodingEasily on YouTube

Video से सीखें – आसान Hindi में

चुनी हुई video: RDBMS भाग 3 – Class XI Commerce IT

▶ Channel subscribe करें