#572 · File handling · Beginner · 35 XP · about 6 min
The pickle module saves Python objects, such as lists and dictionaries, in a binary file and loads them back exactly as they were.
Write save_records(filename, records) that saves every record of the list records into the binary file filename, with one `pickle.dump` call per record, in order. Open the file in 'wb' mode, so anything already in it is replaced. Return how many records you saved.
save_records('class.dat', [[1, 'Asha', 88], [2, 'Ben', 72]]) # returns 2
Reading the file back one record at a time gives [1, 'Asha', 88] and then [2, 'Ben', 72]:
with open('class.dat', 'rb') as f: while True: try: print(pickle.load(f)) except EOFError: break
An empty list of records leaves an empty file.
First solves only, ranked by stars and then time.