在Python中使用pickle和for循环从文件读取 [英] Reading from a file using pickle and for loop in python

查看:573
本文介绍了在Python中使用pickle和for循环从文件读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文件,其中已转储了大量列表.现在我想将此文件加载到内存中并使用其中的数据.我尝试使用"pickle"的"load"方法加载文件,但是由于某种原因,它只是给我文件中的第一项.实际上,我注意到它仅将我的第一个列表加载到内存中,如果要加载整个文件(多个列表),则必须遍历文件,并在每个文件中使用"pickle.load(filename)"我需要的迭代. 问题是我不知道如何用循环(一段时间)来实现它,因为我不知道何时到达文件末尾. 一个例子对我有很大帮助. 谢谢

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

推荐答案

这是怎么回事:

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

这篇关于在Python中使用pickle和for循环从文件读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆