[Tutor] Saving class data to a text file
alan.gauld at freenet.co.uk
Sat Jul 16 21:46:40 CEST 2005
> I have a class that has half a dozen or so data fields. It needs to
> able to save its data to a text file, in a format that's easy to
> with other tools (vi, perl, etc). And needs to be able to load
> back from disk.
Take a look at the OOP topic in my tutor. It includes an examnple
of how to save/load objects to text files.
Other options include the pickle module but it isn't that user
friendly to edit in vi etc...
> Now I have a couple of questions:
> - What is the recommended 'python' way to implement this class?
The native python solution would be to use pickle or shelve modules.
If it must be human friendly too then the approach in my tutor
supplemented by overloading the __repr__() method would work.
> - If what I'm doing is OK, is there an easy way to load a dictionary
> from the string representation without parsing the string manually?
You might try eval() but it is full of security implications, rogue
code in your data could be evaluated and do who knows what kind of
Author of the Learn to Program web tutor
More information about the Tutor