简体   繁体   中英

Reading from a file using pickle and for loop in python

I have a file in which I have dumped a huge number of lists.Now I want to load this file into memory and use the data inside it.I tried to load my file using the "load" method of "pickle", However, for some reason it just gives me the first item in the file. actually I noticed that it only load the my first list into memory and If I want to load my whole file(a number of lists) then I have to iterate over my file and use "pickle.load(filename)" in each of the iterations i take. The problem is that I don't know how to actually implement it with a loop(for or while), because I don't know when I reach the end of my file. an example would help me a lot. thanks

How about this:

lists = []
infile = open('yourfilename.pickle', 'r')
while 1:
    try:
        lists.append(pickle.load(infile))
    except (EOFError, UnpicklingError):
        break
infile.close()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM