我可以流式处理Python pickle列表、元组或其他iterable数据类型吗?

2024-03-29 08:38:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我经常使用逗号/制表符分隔的数据文件,这些文件可能如下所示:

key1,1,2.02,hello,4
key2,3,4.01,goodbye,6
...

我可能会在Python中阅读并预处理成一个列表列表,如下所示:

[ [ key1, 1, 2.02, 'hello', 4 ], [ key2, 3, 4.01, 'goodbye', 6 ] ]

有时,我喜欢将列表列表保存为pickle,因为它保留了我的条目的不同类型。不过,如果pickled文件很大,那么以流式方式读回这个列表列表将非常好。

在Python中,要将文本文件作为流加载,我使用以下方法打印每一行:

with open( 'big_text_file.txt' ) as f:
    for line in f:
        print line

我能为Python列表做些类似的事情吗,例如:

import pickle
with open( 'big_pickled_list.pkl' ) as p:
    for entry in pickle.load_streaming( p ): # note: pickle.load_streaming doesn't exist
        print entry

是否有类似“加载流”的pickle函数?


Tags: 文件inhello列表foraswithline