Pickle加载目录中的所有.pkl文件

时间:2014-03-11 16:11:22

标签: python python-3.x windows-7 pickle

我正在使用Python 3.3 for Windows 7制作Contact Book应用程序。我将联系人信息存储在pickle文件(.pkl)中。我想加载文件夹中的所有pkl文件并使用pickle加载它们,并使用我的GUI显示所有联系人的目录。到目前为止,我的代码是加载文件夹中的所有pickle文件:

for root, dirs, files, in os.walk("LIP Source Files/Contacts/Contact Book"):
    for file in files:
        if file.endswith(".pkl"):
           contacts = file
           print(contacts)
           opencontacts = open(os.getcwd() + "/LIP Source Files/Contacts/Contact Book/" + contacts, 'rb')
           loadedcontacts = pickle.load(contacts)
           print(loadedcontacts)
       else:
          lipgui.msgbox("No contacts found!")

这是lipgui.choicebox()的代码:

     def choicebox(msg="Pick something."
, title=" "
, choices=()
):
"""
Present the user with a list of choices.
return the choice that he selects.
return None if he cancels the selection selection.

@arg msg: the msg to be displayed.
@arg title: the window title
@arg choices: a list or tuple of the choices to be displayed
"""
if len(choices) == 0: choices = ["Program logic error - no choices were specified."]

global __choiceboxMultipleSelect
__choiceboxMultipleSelect = 0
return __choicebox(msg,title,choices)

1 个答案:

答案 0 :(得分:1)

你的问题已经做了一些加载联系人的东西。第loadedcontacts = pickle.load(contacts)行是一种很好的方法。但是pickle.load期望打开的文件而不是文件名。因此,不要传递contacts,而是传递opencontacts

您可以通过在外部循环之前创建列表来将联系人保存在列表中:

allcontacts = [] # Creates an empty list
for root, dirs, files in os.walk("LIP Source Files/Contacts/Contact Book"):
    # Omitted

然后,您将每个联系人附加到该列表中:

            loadedcontacts = pickle.load(opencontacts)
            allcontacts.append(loadedcontacts)

正如旁注:当你不再需要它时,你应该关闭打开的文件。在此示例中,这意味着您在调用opencontacts.close()后调用loadedcontacts = pickle.load(opencontacts)