无法使用 pickle.load() 方法读取附加数据

发布于 2024-09-28 12:09:31 字数 1195 浏览 5 评论 0原文

我编写了两个脚本 Write.pyRead.py

Write.py 以附加模式打开 friends.txt 并获取 nameemailphone 的输入no 然后使用 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()

Read.py

#!/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"]

一定是什么问题,代码看起来没问题。有人能给我指出正确的方向吗?

谢谢。

I have written two scripts Write.py and Read.py.

Write.py opens friends.txt in append mode and takes input for name, email ,phone no and then dumps the dictionary into the file using pickle.dump() method and every thing works fine in this script.

Read.py opens friends.txt in read mode and then loads the contents into dictionary using pickle.load() method and displays the contents of dictionary.

The main problem is in Read.py script, it justs shows the old data, it never shows the appended data ?

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()

Read.py

#!/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"]

What must be the problem, the code looks fine. Can some one point me in the right direction ?

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

九公里浅绿 2024-10-05 12:09:31

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

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)

You have to load from the file several times. Each writing process ignores the others, so it creates a solid block of data independent from the others in the file. If you read it afterwards, it reads only one block at a time. So you could try:

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)
铁憨憨 2024-10-05 12:09:31

每次调用 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(","))

You have to call pickle.load once for each time you called pickle.dump. You write routine does not add an entry to the dictionary, it adds another dictionary. You will have to call pickle.load until the entire file is read, but this will give you several dictionaries you would have to merge. The easier way for this would be just to store the values in CSV-format. This is as simple as

with open("friends.txt", "a") as file:
    file.write("{0},{1},{2}\n".format(name, email, phone))

To load the values into a dictionary you would do:

with open("friends.txt", "a") as file:
    friends = dict((name, (name, email, phone)) for line in file for name, email, phone in line.split(","))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文