简体   繁体   中英

Properly pickling and unpickling a dictionary

I've just started working with the Pickle module in Python 3.4.0 and trying to apply it to a simple program which handles Categories and Words. So far it stores everything as planned, but when I try to load back what I had dumped into the file, the structure appears to be empty:

new_data = int(input("New Data File?\n 1 = Yes\n 0 = No\nChoice: "))
if (new_data == 1):
   f = open('data.txt', 'wb+')
   data_d = {}
   pickle.dump(data_d, f)
   f.close()

PrMenu()
option = int(input("Option: "))
f = open('data.txt', 'rb+')        
d = pickle.load(f)
#Functions inside this menu loop receive the structure (Dictionary)
#and modify it accordingly (add/modify/clear category/word), no
#pickling/unpickling is involved
while (option != 0):
   if (option == 1):
      add_c(d)
   elif (option == 2):
      modify_c(d)
   elif (option == 3):
      clear_c(d)
   elif (option == 4):
      add_w(d)
   elif (option == 5):
      modify_w(d)
   elif (option == 6):
      clear_w(d)
   elif (option == 7):
      pr_cw(d)
   elif (option == 8):
      pr_random(d)

   if (option != 0):
      PrMenu()
      option = int(input("Option: "))


#the output structure would be eg. {category_a:[word1, word2, word3, ...], category_b:[..., ...]}
pickle.dump(d, f)
f.close()
print("End of Program")

I'm not sure where the problem is, I hope I was clear enough.

Thanks.

You are appending data to your file. so the first dataset is the empty dictionary, which you read in, and the second dataset is the filled dictionary, which you never read again. You have to seek back to 0 before writing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM