I can't see the forest through the trees.

I have stored 3 global variables in a dictionary, and associated each
variable with a filename.
Ideally, I want to read the contents of the text files, and store the
contents in the global variables. The globals will be used by another
function.
However, when I do the assignment to varname = fh.readlines(), a new
variable is created, and the reference to the global variable is
overwritten, because the contents of the files are strings, and strings are
immutable.

I see the problem, but not a good solution.


var1=""
var2=""
var3=""

def initGlobals():

   global var1, var2, var3

   fileDict = {'var1.txt':var1, 'var2.txt':var2, 'var3.txt':var3}

   for fn, varname in fileDict.iteritems():
       try:
           try:
               fh=open(fn, 'r')
               #id(varname) # at this point, this id matches the id of the
global variable
               varname = fh.readlines() # this creates a new variable, but
I want to store the file contents in the global var
               #id(varname)                  # this is a new id, the global
var is not updated
               fh.close()
           except IOError:
               print "\nFATAL ERROR occurred reading %s\n" % fn
       finally:
           fh.close()
_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to