0

I have 26 .pkl files at hand, from dict_a.pkl to dict_z.pkl. I want to load them into the memory, so I can compare elements start with a with variable loaded from dict_a.pkl. The reason I want to do this is that each file is really large, if I put them all in one big file, it will be too large to digest. If I load files in an ad hoc style, then it would constantly read disk.

import string
alphabet = string.lowercase

for alpha in alphabet:
   ff = 'dict_'+alpha+'.pkl'
   with open(ff, 'r') as tt:
       temp = cPickle.load(tt)

How can I replace temp variable with dict_a, dict_b in the loop, so I after the loop, I can directly use the variable dict_a to dict_z.

4

1 回答 1

0

您可以使用 glob 模块加载腌制文件,然后逐个处理它们。

    import glob
    import cPickle as pickle
    picklefiles = glob.glob('*.pkl')
    for pklfile in picklefiles:
       with open(pklfile,'rb') as f:
           pklfile = pickle.load(f)

现在您有 26 个字典及其对应的文件名。

编辑:你说得对@Sean我搞砸了第三行它应该是picklefiles而不是pklfiles。我已经更新了代码片段

编辑 2:picklefiles 是一个包含所有扩展名为 .pkl 的文件名的列表。在这种情况下

picklefiles = [  'dict_a.pkl', 'dict_b.pkl', ........ 'dict_z.pkl' ]

在 for 循环中,我打开每个文件并将字典加载到具有相应文件名的字典中。

前任 :

(这是字典类型的变量) dict_a.pkl = { 来自 dict_a.pkl 的值}

于 2014-08-21T06:04:53.177 回答