Python - pickle.load() takes one positional argument (2 given)

冷暖自知 提交于 2019-12-11 12:05:54

问题


This produces an error:

pickle.load() takes one positional argument (2 given)

Here is my code:

import pickle, os.path

created = False

phoneBook = {}
name = input("Please enter a name(or press enter to end input): ")
while name != '':
    number = input("Please enter number: ")
    phoneBook[name] = number
    name = input("Please enter a name(or press enter to end input): ")
    if name == '':
        print("Thank You!")

print("Your phonebook contains the following entries:")
for name, number in phoneBook.items():
    print("%s - %s" % (name, number))

while not created:
    if not os.path.isfile('phonebook.json'):
        phoneBook_Ori = pickle.load('phonebook.json', 'r')
        created = True
    else:
        phoneBook_Ori = pickle.load('phonebook.json', 'w')
        phoneBook_Upd = phoneBook_Ori.update(phoneBook)
        phoneBook_Ori.write(phoneBook_Upd)

phoneBook_Ori.close

Why isn't it pickling data?


回答1:


This is not how you use pickle.load:

phoneBook_Ori = pickle.load('phonebook.json', 'r')

It takes a file object as an argument when de-serializing from a file, not strings.

Try this instead:

# create file object with permissions
with open('phonebook.json', 'r') as f:
    # load using pickle de-serializer
    phoneBook_Ori = pickle.load(f)

Saving is almost the same, make sure you have the updated phonebook in scope:

with open('phonebook.json', 'wb') as f:
    phoneBook_Ori = pickle.dump(phonebook, f)

As for the rest of the code, you may want to read another answer I've given that is very similar.



来源:https://stackoverflow.com/questions/28812686/python-pickle-load-takes-one-positional-argument-2-given

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!