luciferchase
luciferchase

Reputation: 559

How to read complete file usind pickle.load()?

Suppose, I want to read the complete file using pickle.load(), not just a single line. I know I can use try - except but is there any other method to read it?
I am using this:


    import pickle
    d = {}
    for i in range(2):
        roll_no = int(input("Enter roll no: "))
        name = input("Enter name: ")
        d[roll_no] = name

     f = open("test.dat", "ab")
     pickle.dump(d, f)
     f.close()

     f = open("test.dat", "rb")
     while True:
         try:
            print(pickle.load(f))
        except EOFError:
            break

Upvotes: 0

Views: 1006

Answers (2)

tdelaney
tdelaney

Reputation: 77347

You can use file.tell to see if you are at EOF

f = open("test.dat", "rb")
# go to end of file and get position
size = f.seek(0, 2)
# now return to the front and pull pickle records
f.seek(0)    
while f.tell() < size:
    print(pickle.load(f))

Upvotes: 1

michaeldel
michaeldel

Reputation: 2385

The official Python library does not support this within a single instruction. You can define your own helper function though:

import io
import pickle

from typing import List

def unpickle(file: io.IOBase) -> List[object]:
    result = []
    while True:
        try:
            result.append(pickle.load(file))
        except EOFError:
            break
    return result

You can then call it like this

with open('data.pickle', 'rb') as f:
    objects = unpickle(f)

objects will contain all the objects that have been serialized in data.pickle here.

Upvotes: 1

Related Questions