开发者

Can't read appended data using pickle.load() method

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.


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)


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(","))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜