Python Can';t使用pickle.load()方法读取附加数据

Python Can';t使用pickle.load()方法读取附加数据,python,file-io,dictionary,pickle,Python,File Io,Dictionary,Pickle,我已经写了两个脚本Write.py和Read.py Write.py在追加模式下打开friends.txt,为name、email、电话号码进行输入,然后使用pickle.dump()方法将字典转储到文件中,在这个脚本中一切都很好 Read.py以读取模式打开friends.txt,然后使用pickle.load()方法将内容加载到词典中,并显示词典的内容 主要问题是在Read.py脚本中,它只显示旧数据,而从不显示附加数据 Write.py #!/usr/bin/python import

我已经写了两个脚本
Write.py
Read.py

Write.py
在追加模式下打开
friends.txt
,为
name
email
电话号码
进行输入,然后使用
pickle.dump()
方法将字典转储到文件中,在这个脚本中一切都很好

Read.py
以读取模式打开
friends.txt
,然后使用
pickle.load()
方法将内容加载到词典中,并显示词典的内容

主要问题是在
Read.py
脚本中,它只显示旧数据,而从不显示附加数据

Write.py

#!/usr/bin/python

import pickle

ans = "y"
friends={}
file = open("friends.txt", "a")
while ans == "y":
    name = raw_input("Enter name : ")
    email = raw_input("Enter email : ")
    phone = raw_input("Enter Phone no : ")

    friends[name] = {"Name": name, "Email": email, "Phone": phone}

    ans = raw_input("Do you want to add another record (y/n) ? :")

pickle.dump(friends, file)
file.close()
#!/usr/bin/py

import pickle

file = open("friends.txt", "r")

friend = pickle.load(file)

file.close()

for person in friend:
    print friend[person]["Name"], "\t", friend[person]["Email"] , "\t", friend[person]["Phone"]
Read.py

#!/usr/bin/python

import pickle

ans = "y"
friends={}
file = open("friends.txt", "a")
while ans == "y":
    name = raw_input("Enter name : ")
    email = raw_input("Enter email : ")
    phone = raw_input("Enter Phone no : ")

    friends[name] = {"Name": name, "Email": email, "Phone": phone}

    ans = raw_input("Do you want to add another record (y/n) ? :")

pickle.dump(friends, file)
file.close()
#!/usr/bin/py

import pickle

file = open("friends.txt", "r")

friend = pickle.load(file)

file.close()

for person in friend:
    print friend[person]["Name"], "\t", friend[person]["Email"] , "\t", friend[person]["Phone"]
一定是什么问题,代码看起来不错。有人能给我指出正确的方向吗


谢谢。

每次调用
pickle.dump
时,您必须调用
pickle.load
一次。您编写的例程不会向字典中添加条目,而是添加另一个字典。在读取整个文件之前,您必须调用
pickle.load
,但这将为您提供几个必须合并的词典。更简单的方法是以CSV格式存储值。这很简单

with open("friends.txt", "a") as file:
    file.write("{0},{1},{2}\n".format(name, email, phone))
要将这些值加载到字典中,请执行以下操作:

with open("friends.txt", "a") as file:
    friends = dict((name, (name, email, phone)) for line in file for name, email, phone in line.split(","))

您必须多次从该文件加载。每个写入过程都会忽略其他过程,因此它会创建一个独立于文件中其他过程的实心数据块。如果以后再读,它一次只能读一个块。所以你可以试试:

import pickle

friend = {}
with open('friends.txt') as f:
    while 1:
        try:
            friend.update(pickle.load(f))
        except EOFError:
            break # no more data in the file

for person in friend.values():
    print '{Name}\t{Email}\t{Phone}'.format(**person)

我从来都不知道,只要将
关键字一起使用,就可以避免使用
file.close()
。非常感谢。@Searock-是的,您有一个清晰的缩进块,文件就是在这里打开的。只要快速阅读您需要的所有内容,它就会关闭。如何使用
pickle.load()
附加以键为名称的字典。dictionary
AttributeError给了我这个错误:“dict”对象没有属性“append”
@Searock-你说得对,我现在编辑了我的答案,并为你提供了更好的迭代和结果展示。