我想以instance's attributes
编程方式编译从外部(.csv)文件导入数据.到目前为止,我可以手动执行一个实例.使用此工作流程:
class RS: #the calss has the importer method and many attributes ... #workflow starts here a=RS() #I create the instance a.importer('pathofthefile') #the importer method fills the attributes of the instance with the exeternal file #ends here and restart... b=RS() b.importer('path...
我想以编程方式创建实例并填充它们importer
.如何class
在大量文件上迭代此过程?例如,listdir
用于导入文件夹中的所有文件?我喜欢这样的东西来创建实例:
for i in 'abcd': eval('%s=RS()' %(i))
但当然似乎不起作用..
您不应该将它们读入具有不同名称的变量 - 您将如何使用变量?
而是将它们读入具有单个名称的数据结构中.
让我们把实例的实际过程和导入到函数中:
def read_instance(filename): instance = RS() instance.importer(filename) return instance
然后你可以做一个列表:
instances = [read_instance(filename) for filename in 'abcd'] print len(instances) # Prints 4 print instance[0] # Prints the first print instance[1] # Prints the second, etc
或者字典:
instances = {filename: read_instance(filename) for filename in 'abcd'} print instances['c'] # Prints the instance corresponding to filename 'c'