[Tutor] Assigning a variable stored in a dictionary

Tony Cappellini cappy2112 at gmail.com
Thu Jan 4 21:36:54 CET 2007


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()
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070104/1bf1c90f/attachment.htm 


More information about the Tutor mailing list