generating unique variable name via loops
python.list at tim.thechases.com
Tue Nov 4 16:05:30 CET 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
with open("data.txt", "rb") as f:
dr = csv.DictReader(f)
for row in dr:
If the file format is more complex, it's often useful to create a
generator to simplify the logic:
self.name = name
self.salary = salary
self.shift = shift
def various_person_methods(self, ...):
"build Person objects as you iterate over the file"
for row in file:
person = Person( ... )
with open("data.txt", "r"):
for person in people_from_file(f):
You can then reuse that generator with multiple files if you need.
More information about the Python-list