views:

30

answers:

2

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.

+1  A: 

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(","))
Space_C0wb0y
+1 I really appreciate your efforts in showing me CSV-format example : )
Searock
@Searock: You never know :)
Space_C0wb0y
@Space_C0wb0y How can you say that, I have always voted up your answers : )
Searock
+1  A: 

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)
eumiro
I never knew i could avoid use of `file.close()` just by using `with` keyword. Thanks a lot.
Searock
@Searock - yes, and you have a clearly indented block, where the file is opened. Just quickly read all you need and it will close.
eumiro
@eumiro How do I append dictionaries with key as name using `pickle.load()`. It gives me this error for dictionary `AttributeError : 'dict' object has no attribute 'append'`
Searock
@Searock - you're right, I have now edited my answer and offered you also a better iteration and presentation of the results.
eumiro
@eumiro Thanks a lot again, I wished you were my professor : (
Searock