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

Why a text file? If you simply want to preserve information from session to session, there are three ways

  1. What you suggested: Write the data to a text file
  2. Pickle , Python's object serializer module (actually: Use cPickle)
  3. 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.

Why a text file? If you simply want to preserve information from session to session, there are three ways

  1. What you suggested: Write the data to a text file
  2. Pickle , Python's object serializer module (actually: Use cPickle)
  3. 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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.