generating unique variable name via loops

Tim Chase python.list at tim.thechases.com
Tue Nov 4 10:05:30 EST 2014


On 2014-11-04 05:53, Fatih Güven wrote:
> > > for x in range(1,10):
> > >     exec("list%d = []" % x)
> > 
> > Why would you do this?
> 
> I have a structured and repetitive data. I want to read a .txt file
> line by line and classified it to call easily. For example
> employee1 has a name, a salary, shift, age etc. and employee2 and
> other 101 employee have all of it. 
> 
> Call employee1.name or employee2.salary and assign it to a new
> variable, something etc. -- 

This sounds remarkably like a CSV or tab-delimited file.  If so, the
way to do it would be

  import csv
  with open("data.txt", "rb") as f:
    dr = csv.DictReader(f)
    for row in dr:
      do_something(row["Name"], row["salary"])


If the file format is more complex, it's often useful to create a
generator to simplify the logic:

  class Person:
    def __init__(self,
        name="",
        salary=0,
        shift="",
        ):
      self.name = name
      self.salary = salary
      self.shift = shift
    def various_person_methods(self, ...):
      pass

  def people_from_file(f):
    "build Person objects as you iterate over the file"
    for row in file:
      person = Person( ... )
      yield person

  with open("data.txt", "r"):
    for person in people_from_file(f):
      do_something(person)

You can then reuse that generator with multiple files if you need.

-tkc







More information about the Python-list mailing list