'Why does pickle only reads the first line of the file?

I made a program that stores some data into a file with Pickle

Here is what the file looks like:

ÄX
(7836)q.ÄX
(13289)q.ÄX
(0928)q.ÄX
(26)q.ÄX
(7893)q.ÄX
(3883)q.ÄX
(1982)q.ÄX

what it is is not important

but when I try to read it with:

data = pickle.load(open("num.txt", "rb"))
print(data)

this is the output:

(7836)

while the expected result is:

(7836)
(13289)
(0928)
(26)
(7893)
(3883)
(1982)

How do I fix this?



Solution 1:[1]

The following is @jsbueno's answer, worked for me.To be found here +more answers.

Pickle serializes a single object at a time, and reads back a single object - the pickled data is recorded in sequence on the file.

If you simply do pickle.load you should be reading the first object serialized into the file (not the last one as you've written).

After unserializing the first object, the file-pointer is at the beggining of the next object - if you simply call pickle.load again, it will read that next object - do that until the end of the file.

objects = []
with (open("myfile", "rb")) as openfile:
    while True:
        try:
            objects.append(pickle.load(openfile))
        except EOFError:
            break

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 B Shmid