[Tutor] [Fwd: re: turn a file into a dictionary]

Colin Campbell CCampbell@ede.org
Mon, 30 Sep 2002 09:58:01 -0600


-------- Original Message --------
Subject: re: turn a file into a dictionary
Date: Sun, 29 Sep 2002 12:29:07 +0000
From: Charlie Clark <charlie@begeistert.org>
To: tutor@python.org
CC: CCampbell@ede.org
References: <20020929093802.26719.4729.Mailman@mail.python.org>

<snipped some embarassment!)
Magnus has already answered the question but I thought I'd mention a couple
of alternatives.

First of all, as Magnus points out, you could do:

myFileText = file(filename).read()
d = eval("{ %s }" % myFileText)

He advises you against this - the reason being that 'eval' won't do any
security checking. It's conceivable, therefore, that your file contains
some text will might be dangerous when run as Python code. This kind of
security risk is common to all programming languages notably cgi and SQL.

What do you want to do with your file? ie. how do you want to manage data
in the future: by direct manipulation of the textfile in a text editor or
through your program? If you still need to edit the textfile you're best
following Magnus' suggestion. If not you will might consider using the
pickle or shelve module to store your data and thus avoid the overhead of
converting from string to dictionary and back again. Pickle and shelve use
textfiles to store binary data such as dictionaries. Pickle is a generic
tool for storing all kinds of Python objects in textfiles whereas shelve is
specifically for dictionaries. You can edit the textfiles thus created if
you are really careful but it's not advisable. XML-Pickle may give you the
best of both worlds allowing you to manage your data either in a text
editor or in a program.


The file is an access control list for a set of financial statements, 
consisting of sheets in an Excel workbook. At present, I have a VBA 
macro which gets username from the network login, looks them up in the 
ACL, then hides all but the permitted sheets. The macro is stored in the 
same workbook, so it is defeated by disabling macros. I could simply 
build another workbook to contain the macro only, and have it act on the 
financial statements, but I want to combine all my reporting tools 
behind a Python front end.

The ACL file is relatively static and small, so I think what I will wind 
up doing is a cross between Magnus' and Charlie's advice: I'll use 
interactive Python one time to create and maintain the dictionary, then 
shelve it, so the front-end to the report system just needs to unshelve it.

Many thanks to both Magnus and Charlie for patiently dealing with 
chowder-headed ideas!

Colin

--
A closed mouth gathers no feet.
-Unattributed