[Tutor] cPickle and shjelving

Hugo Arts hugo.yoshi at gmail.com
Wed Aug 24 13:32:25 CEST 2011


On Wed, Aug 24, 2011 at 11:26 AM, Warren P. Jones <WPJones at ewation.co.za> wrote:
> Hi,
>
> I am new to python. I am having slight issue in using the cPickle and
> shelving function.
>
> Here is what i want the program need to do:
>
> Open an file with employees in it with relevant information like: employee
> number, surname and department. I also need to add an employee with the
> relevant information without rewriting the current data.
>
> I have tried the code but not completely sure what i am doing wrong.
>
> Here is the code that i tried:
>
> # Defines
> pickles["employee_num"]
>
>     pickle_file = shelve.open("empl.dat")
>            print "Add new Employee"
>            employee_num = raw_input("\nEmployee number: ")
>            surname = raw_input("Surname: ")
>            name = raw_input("Name: ")
>            department = raw_input("Department: ")
>
>            ########################
>
>            #    Storing DATA      #
>
>            ########################
>
>            cPickles.dump(employee_num, emp1.dat)
>            print key, "-",pickles[key]
>            pickles.sync () # Makes sure date is written
>
> Can you please help me in solving this issue?
>
> Kind regards
>
> Warren  Jones
>

That code makes very little sense. The indentation is wrong, and some
variables are never declared. Is that the full code? Also, shelve
already uses cPickle internally, so you don't need to use it
separately. Once you open a shelf, you can use it as a regular
dictionary object afterward:

shelf = shelve.open("empl.dat")
employee_num = raw_input("\nEmployee number: ")
shelf[employee_num] = {
            "surname": raw_input("Surname: "),
            "name": raw_input("Name: "),
            "department": raw_input("Department: ")
}
shelf.close()


More information about the Tutor mailing list