Getting Variables from a file

emile at fenx.com emile at fenx.com
Sun May 28 01:43:27 CEST 2000


This should get you started:

vars = """dof = 8
elements = 10
mesh_dof = 300"""

for line in vars.split("\n"):
  exec (line)

print dof,elements,mesh_dof

You should be careful exec'ing things though, so maybe:

vars = """dof = 8
elements = 10
mesh_dof = 300"""

for line in vars.split("\n"):
  try:
    k,v = line.split(" = ")
    exec (line)
  except:
    # doexn't parse out as tuple w/ interspersed =
    pass

print dof,elements,mesh_dof

is safer.  I'm sure there's still a hole in that, I just
don't see it right now.


Emile van Sebille
emile at fenx.com


Curtis Jensen <cjensen at bioeng.ucsd.edu> wrote in message
news:<39305B84.A06745E9 at bioeng.ucsd.edu>...
> I have a text file of the form:
> 
> (var = integer)
> dof = 8
> elements = 10
> mesh_dof = 300
> .
> .
> .
> .
> 
> I want to read the file from within Python and then create a variable in
> python of the same name as what is in the text file, and holding the
> assigned value.  Assuming I don't already know the names of the
> varialbes; how do I do this?  I can do the file I/O, but how do I change
> a character string into a variable name?  Thanks.
> 
> -- 
> Curtis Jensen
> cjensen at bioeng.ucsd.edu
> http://www-bioeng.ucsd.edu/~cjensen/
> FAX (425) 740-1451
> -- 
> http://www.python.org/mailman/listinfo/python-list
>




More information about the Python-list mailing list