954,510 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Writing a dict to a .txt doc so that it can be recalled as a dict?

So I've finally fixed up the functionality of an address book I've been writing (not on to utilizing a GUI yet of course though.)However to save or reclaim the data from the last use of the address book I, obviously, need to write and reclaim it from a .txt file, I understand how to write and read, however I'm not sure how to write so when it is read I can make it back into a dictionary. Any ideas? here's how I'm writing so far.

for line in AB.keys():
    line=line+'\n '
    print(line,file=f)
for line in AB.values():
    for string in line:
        print(string+'\n',file=f)
f.close
pyguy62
Posting Whiz
353 posts since Aug 2011
Reputation Points: 34
Solved Threads: 19
 

Why a text file? If you simply want to preserve information from session to session, there are three waysWhat you suggested: Write the data to a text file
Pickle , Python's object serializer module (actually: Use cPickle)
Use a database
I recommend you use pickle. However if you choose to move ahead with option 1, note the "%r" formatting directive for example:

s = {'one':'uno', 2:'dos', 'cat': 'gato'}
print ("%r"%s)

You can then use the eval builtin function to recover the data. Beware of quote issues.

griswolf
Veteran Poster
1,165 posts since Apr 2010
Reputation Points: 344
Solved Threads: 256
 
Why a text file? If you simply want to preserve information from session to session, there are three ways
  • What you suggested: Write the data to a text file
  • Pickle , Python's object serializer module (actually: Use cPickle)
  • Use a database

I recommend you use pickle. However if you choose to move ahead with option 1, note the "%r" formatting directive for example:

s = {'one':'uno', 2:'dos', 'cat': 'gato'}
print ("%r"%s)

You can then use the eval builtin function to recover the data. Beware of quote issues.


thank you, what does that look like in code? and where does it save the data? I'm reading over this doc, but it's not really giving me the applied knowledge I need to understand how to utilize it.

pyguy62
Posting Whiz
353 posts since Aug 2011
Reputation Points: 34
Solved Threads: 19
 

figured it out. thanks.

pyguy62
Posting Whiz
353 posts since Aug 2011
Reputation Points: 34
Solved Threads: 19
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: