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

Dani AI

Generated

A concise, practical summary that fills gaps from the thread and shows safe, repeatable ways to persist a Python dict.

was right that serializing the whole object is easiest; , since you solved it yourself, here are options you can reuse later and common pitfalls to avoid.

JSON — portable and human-readable, use this when your dict keys are strings and values are basic types (str, int, list, dict, bool, None). Example (Python 3):

import json

with open('addressbook.json', 'w', encoding='utf-8') as f:
    json.dump(address_book, f, ensure_ascii=False, indent=2)

with open('addressbook.json', 'r', encoding='utf-8') as f:
    address_book = json.load(f)

Note: JSON requires string keys. If you have non-string keys, convert via list(address_book.items()) before saving and rebuild with dict(...) after loading.

Pickle — preserves arbitrary Python objects and is convenient for pure-Python data. Use binary mode and pickle.HIGHEST_PROTOCOL. Strong caution: never unpickle data from untrusted sources (it can execute code).

import pickle

with open('addressbook.pkl', 'wb') as f:
    pickle.dump(address_book, f, protocol=pickle.HIGHEST_PROTOCOL)

with open('addressbook.pkl', 'rb') as f:
    address_book = pickle.load(f)

Other options: shelve gives simple key/value persistence without manual serialization; SQLite is better when you need queries or concurrency.

Troubleshooting tips: always use with open(...) so files close reliably, handle exceptions around load/dump, back up files before overwriting, and consider data migrations (version your saved format) if your structure may change. Avoid eval on file contents — it’s unsafe and brittle.

Recommended Answers

All 3 Replies

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.

figured it out. thanks.

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.