Binary Files with pickle
This is a free course. Log in to run the code exercises and track your progress.
Binary Files with pickle
The pickle module turns a Python object (a list, a dictionary, a tuple...) into bytes and back. Turning it into bytes is pickling (serialisation); restoring it is unpickling. Pickled data goes into a file opened in a binary mode.
pickle.dump(obj, file): write one object.pickle.load(file): read the next object; raisesEOFErrorwhen there are no more.
import pickle
with open("students.dat", "wb") as f: # write records
pickle.dump({"roll": 1, "name": "Asha", "marks": 88}, f)
pickle.dump({"roll": 2, "name": "Ravi", "marks": 72}, f)
with open("students.dat", "rb") as f: # search for roll 2
try:
while True:
rec = pickle.load(f)
if rec["roll"] == 2:
print(rec["name"])
except EOFError:
pass
To append records open the file with "ab". To update a record, read all the records into a list, change the one you want, and write the whole list back with "wb" (or, with "rb+", seek() back to the record's position, which works only if its pickled size does not change).
Read n records roll name marks and pickle.dump() each one, as a list, into an in-memory binary file. Then read the file back with pickle.load() until EOFError and print the records whose marks are 75 or more, as roll name marks.
import io
import pickle
f = io.BytesIO() # stands in for open("students.dat", "wb+")
for _ in range(int(input())):
roll, name, marks = input().split()
pickle.dump([int(roll), name, int(marks)], f)
f.seek(0)
# load records until EOFError and print the ones with marks >= 75Log in to edit and run this code.