Question

I am making a Contact Book application in Python 3.3 for Windows 7. I am storing the contacts info in pickle files (.pkl). I want to load all the pkl files in the folder and load them with pickle and also display a directory of all the contacts with my GUI. Here is my code so far to load all pickle files in the folder:

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!")

Here's the code for 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)
Était-ce utile?

La solution

Your question already does some stuff to load the contacts. The line loadedcontacts = pickle.load(contacts) is a good approach. But pickle.load expects an opened file rather than a file name. So instead of passing contacts you pass opencontacts.

You can save the contacts then in a list by creating a list before the outer loop:

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

Then you append every contact you unpickle to that list:

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

And just as a side note: You should close the opened file when you don't need it anymore. In this example this means that you call opencontacts.close() after the call to loadedcontacts = pickle.load(opencontacts).

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top