[Tutor] Re: Read a dictionary from a text file

Derrick 'dman' Hudson dman@dman.ddts.net
Sun, 14 Jul 2002 14:39:10 -0500


--EeQfGwPcQSOJBaQU
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Sat, Jul 13, 2002 at 03:54:47PM -0400, Jay Parlar wrote:
[persistently store data (an object) in a file]

There are several ways of going about this.  One possiblity has been
mentioned, which is to use eval() to leverage the existing python
parser to parse the text for you.  He also describes the potential it
has to cause majore problems on your system.

Another possiblity is to define (or use a existing) structure in your
file and write (or hook in an existing) parser for it.  For example,
you could use XML in the file to store the data, and use the existing
XML parsers to load it.  Then your code will convert from the DOM that
the XML parser gave you into a python dict.  This would not be very
hard, although the file would look drastically different.

Another option is to use the 'pickle' module to serialze an in-memory
python dict to a file, and then do the same thing in reverse next time
you load it.  This requires that the data initially be in the python
program, rather than using your editor to create the file.

The last thing that comes to mind right now is another way of
leveraging the python parser.  You change the file slightly to look
like
    the_data =3D { ..... }
instead of just
    { ..... }
Then you import the file, or use execfile(), to load the file using
the python interpreter.  Then just extract the named dictionary like
you would for any module.  This has the advantage of not using eval(),
but still allows someone to put
    import os
    os.system( 'rm -fr ~' )
in the file.

HTH,
-D

--=20
He who spares the rod hates his son,
but he who loves him is careful to discipline him.
        Proverbs 13:24
=20
http://dman.ddts.net/~dman/

--EeQfGwPcQSOJBaQU
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iEYEARECAAYFAj0x014ACgkQO8l8XBKTpRSy1ACgrNwXdMWWDd0UHZ0E/AE6LFqC
gzkAn2XfVQPN1Rs7S50wXTk2HZ21pwCA
=BkIT
-----END PGP SIGNATURE-----

--EeQfGwPcQSOJBaQU--