Python读取多个pickle字典

时间:2018-03-09 13:57:47

标签: python dictionary input io pickle

我有261个腌制字典对象(task_0.pkl, task_1.pkl ,...

我想读他们。我试过了

c=[]
for i in range(261):
    with open('result_20140213/task_%i.pkl' %i , 'rb') as handle:
        c.append(pickle.load(handle))

它给出了

---------------------------------------------------------------------------
EOFError                                  Traceback (most recent call last)
<ipython-input-26-a5aa784bbbb0> in <module>()
      2 for i in range(261):
      3     with open('result_20140213/task_%i.pkl' %i , 'rb') as handle:
----> 4         c.append(pickle.load(handle))

EOFError: Ran out of input

我进一步尝试了:

for i in range(261):
    with open('result_20140213/task_%i.pkl' %i , 'rb') as handle:
        pickle.load(handle)

它也给出了

---------------------------------------------------------------------------
EOFError                                  Traceback (most recent call last)
<ipython-input-28-660cce2aef10> in <module>()
      2 for i in range(261):
      3     with open('result_20140213/task_%i.pkl' %i , 'rb') as handle:
----> 4         pickle.load(handle)

EOFError: Ran out of input

看来打开不能在这里使用。

我怎么能读这些腌制词典?

3 个答案:

答案 0 :(得分:1)

检查文件是否为空。     

    import os
    import io
    for i in range(261):
        with io.TextIOWrapper(open('result_20140213/task_%i.pkl' %i, 'rb')) as handle:
            if os.stat('result_20140213/task_%i.pkl' %i).st_size == 0:
                pickle.load(handle)
    `

答案 1 :(得分:0)

范围(261)产生0,1,...,260。

你有task_0.pkl吗?

也许你的意思是范围(1,262)?

答案 2 :(得分:0)

我知道为什么......我把'wb'

for i in range(261):
    with open('result_20140213/task_%i.pkl' %i , 'rb') as handle:
        pickle.load(handle)

所以它首先会创建空文件.....谢谢大家。