我正在为Windows 7制作Python 3.3中的联系人簿应用程序。我将联系人信息存储在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)
你的问题已经做了一些东西来加载联系人。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
然后你将所有你解pickle的联系人添加到该列表中:
loadedcontacts = pickle.load(opencontacts)
allcontacts.append(loadedcontacts)
作为旁注:当你不再需要打开的文件时,你应该关闭它。在本例中,这意味着在调用loadedcontacts = pickle.load(opencontacts)
之后调用opencontacts.close()
。