How to count several serialized objects in the list using the pickle function? Tried to count in this way:

data2 = [] with open("AllOutputMethodsObj.txt", "rb") as f: for _ in range(pickle.load(f)): data2.append(pickle.load(f)) print (str(data2)) 

But at the output I get an error:

 for _ in range(pickle.load(f)): EOFError: Ran out of input 

The number of serialized objects I do not know. A file with an unknown number of serialized objects is fed to the input.

    2 answers 2

     import pickle objs = dict(a=1, b=2), [3, 4], {5, 6} pickle.dump(objs, open('test.tt', 'wb')) for ob in pickle.load(open('test.tt', 'rb')): print(ob) 
    • Complete your answer with a solution. - Yuri
    • If you compile by correcting your code, for ob in pickle.load (open ('AllOutputMethodsObj.txt', 'rb')): print (ob) then I get a dictionary without the value of the keys: Method name Line number Line Method number in the project Method number in file File path Construction - user200355

    pickle always contains exactly one object. In particular, this object can be a collection of other objects, for example, a tuple or even an iterator .

     import pickle with open("objects.pickle", "rb") as file: a, b, c = pickle.load(file) 

    At the same time, objects were also saved using exactly one pickle.dump() call:

     with open("objects.pickle", "wb") as file: pickle.dump([a, b, c], file) 

    If you want to serialize objects at different times, you can try shelve module :

     import shelve with shelve.open('objects') as db: db['a'] = a ... db['b'] = b 

    It works simultaneously in both read and write:

     with shelve.open('objects') as db: a = db['a'] # read a += 1 # modify db['a'] = a # write back