Saving a Dictionary of Pointers to File

I'm trying to create a family tree in python, and I want to create a dictionary of Persons, where the key is the person's first name and the value is a Person object for that name.

I can create the dictionary fine, and I can save it fine using the below code.

import os, ast

myFile = open( FILE, "r+" )     # Opens the file for reading and writing

tree = myFile.read()

if tree == "":
    tree = {}
else:
    tree = ast.literal_eval(tree)


def save():
    myFile.write(str(tree))
    myFile.close()

However, when I reload my program and try to read in the dictionary, I get the following error:

File "<unknown>", line 1
    {'Charlie': <__main__.Person object at 0x00000000032DB860>}
                ^
SyntaxError: invalid syntax

I suspect that the evaluator can't recognize the object because once the program closes the pointer no longer exists. Is there a way I can save my dictionary so that I can reload it and have access to all my Person objects' data without losing it each time my program closes?

Answers


ast.literal_eval is not meant for evaluating and understanding custom objects. It's used to evaluate strings and literals safely. You need to serialize your data by using something like pickle.

>>> import pickle
>>> class Person(object):
...     def __init__(self, name):
...         self.name = name  
... 
>>> persons = {'Charlie': Person('Charlie')}
>>> with open(FILE, "wb") as my_file:
...     pickle.dump(persons, my_file)
...
>>> with open(FILE, "rb") as f:
...     result = pickle.load(f)
...     
... 
>>> result
{'Charlie': <__main__.Person object at 0x1598bd0>}

When you have large (or many) objects, you can use cPickle in which the pickling is done in C instead of python thus providing a major speed increase.

If object serialization is something you have not heard about before, please read this.


Need Your Help

Problem in java ftp code

java ftp

i'm getting error in java ftp code.

How to change cancel button tint color of UISearchBar in iOS7

ios iphone objective-c uisearchbar

I want to change tint color of Textfield to blue color and cancel button tint color of UISearchBar to white color.