Receita: Exemplo de uso do Pickle
Código de exemplo sobre o uso do Pickle. É um mini gerenciador para grade curricular. Ele usa o cPickle, por questão de desempenho, mas nada que impeça de usá-lo com o Pickle normal.
Código
1 import cPickle
2
3
4 def write_file():
5 """
6 Funcao que escreve num arquivo um dicionario.
7 Isto eh, escreve um arquivo binario de um objeto
8 Python usando o Pickle
9 """
10 CIT = ["Academic Computer Skills", "Database Management", "Intro to Computer scince",\
11 "ACCESS","Systems Analysis and Design", "Visual Basic",\
12 "Intermediate Visual Basic", "Decision Support Using Excel"]
13 pickle_file = open("pickles1.dat","w")
14
15 cPickle.dump(CIT, pickle_file)
16 print "A file has been created and the required specifications have been added"
17 pickle_file.close()
18
19
20 def read_file():
21 """
22 Le o dicionario do arquivo.
23 """
24 pickle_file = open("pickles1.dat","r")
25 CIT = cPickle.load(pickle_file)
26 pickle_file.close()
27
28 for course in CIT:
29 print CIT.index(course), "-", course
30
31
32 def delete_file():
33 """
34 Deleta uma entrada do dicionario
35 Tambem atualiza no arquivo.
36 """
37 word_delete = int(raw_input("Which record do u want to delete?[key of the record]: "))
38
39 pickle_file = open("pickles1.dat", "r")
40 CIT = cPickle.load(pickle_file)
41 pickle_file.close()
42
43 try:
44 CIT.pop(word_delete)
45 pickle_file = open("pickles1.dat","w")
46 cPickle.dump(CIT, pickle_file)
47 pickle_file.close()
48 except:
49 print "There isnt a record with this key"
50
51
52 def add_record():
53 """
54 Adiciona um registro ao dicionario.
55 Tambem atualiza o arquivo
56 """
57 pickle_file = open("pickles1.dat", "r")
58 CIT = cPickle.load(pickle_file)
59 CIT.append("SQL Programming")
60 CIT.append("Database Programming")
61 pickle_file.close()
62
63 pickle_file = open("pickles1.dat","w")
64 cPickle.dump(CIT, pickle_file)
65 print "New data was added to the file"
66 pickle_file.close()
67
68
69 def display_instructions():
70 """Display the Main menue"""
71 print \
72 """
73 Main Menu:
74
75 1. Exit
76 2. Create a new file and add specifications
77 3. Add more courses to the file
78 4. Read the file
79 5. Delete a course
80 6. Display instructions
81
82 """
83
84
85 # exit the program >>> 1 <<<
86 def over_program():
87 """Exit the program"""
88 print "Good Bye!"
89
90
91 def main():
92 choice = None
93 display_instructions()
94
95
96 while choice != 1:
97 choice = raw_input("\nChoice: ")
98 if choice == "1":
99 over_program()
100 break
101
102 elif choice == "2":
103 write_file()
104
105 elif choice == "3":
106 add_record()
107
108 elif choice == "4":
109 read_file()
110
111 elif choice == "5":
112 delete_file()
113
114 elif choice == "6":
115 display_instructions()
116
117 else:
118 print "\nSorry, but %s isn! 't a valid choice."%(choice)
119
120
121 main()
122 raw_input("Press Enter Key to Exit.")
Volta para CookBook.
Murtog