[Tutor] Reading Input Data
Kent Johnson
kent37 at tds.net
Tue Jan 15 22:25:09 CET 2008
Michael Langford wrote:
> for subscript,line in enumerate(file("file.csv")):
> s = line.split(",")[1]
> try:
> f = float(s)
> locals()["x%i" % subscript]=f
> except:
> locals()["x%i" % subscript]=s
Don't do this!
For one thing, writing to locals() doesn't always work. Specifically,
writing to locals() inside a function does *not* affect the local namespace:
In [28]: def foo():
....: locals()['x'] = 1
....: print x
....:
....:
In [29]: foo()
------------------------------------------------------------
Traceback (most recent call last):
File "<ipython console>", line 1, in <module>
File "<ipython console>", line 3, in foo
<type 'exceptions.NameError'>: global name 'x' is not defined
Writing to globals() might be marginally better but not much. (When not
in a function, locals() is actually the same as globals() and the above
code will work.)
In most cases where someone is trying to assign a bunch of names like
this, a better solution is to use a dictionary (or possibly a list) to
hold the data.
Kent
More information about the Tutor
mailing list