简体   繁体   English

在python中使用pickle和for循环从文件中读取

[英]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. 我有一个文件,我已经转储了大量的lists.Now我想将此文件加载到内存并使用其中的数据。我试图使用“pickle”的“加载”方法加载我的文件,但是,出于某种原因,它只是给了我文件中的第一项。 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. 实际上我注意到它只将我的第一个列表加载到内存中,如果我想加载我的整个文件(多个列表),那么我必须迭代我的文件并在每个文件中使用“pickle.load(filename)”迭代我采取。 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. 问题是我不知道如何用循环(for或while)实际实现它,因为我不知道何时到达文件的末尾。 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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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