Import Issue

A.T.Hofkamp hat at se-126.se.wtb.tue.nl
Fri Jun 2 06:55:10 EDT 2006


On 2006-06-02, praveenkumar.117 at gmail.com <praveenkumar.117 at gmail.com> wrote:
> Hi all,
> After doing import file i am updating that file. Later i am
> accessing a dictionary contained in that
> file. Eventhough changes are reflected in the file... When i
> access a dictionary those changes are
> not there. I believe that it is accessing from the object
> file that is created when i did import at
> the start of the script. I will be kind enough if somebody
> suggest solution to this problem.

The easiest suggestion I can make is "don't do that".
An import statement is intended for importing static Python code, not for
importing dynamic data such as dictionaries that you update while running.

Your application is much easier to understand if you keep Python code and data
in seperate files.
For this, there are several options:

A.
If you stick to Python syntax of your data, you can load such files with 'open'
and 'read', followed by 'eval'

fp = open('datafile','r')
datatext = fp.read()
fp.close()
print eval datatext

B.
If you don't care about accessing the data outside Python, you can use the
pickle module to load and save the data.
(please read http://docs.python.org/lib/module-pickle.html for details).

C.
Last but not least, you can define your own data format, and write custom load
and save routines for accessing the data file. This approach is highly
flexible, but it does cost effort to write the routines.


Hope this answer your question,
Albert




More information about the Python-list mailing list