我想编译实例的属性
,以编程方式从外部 (.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...
我想以编程方式创建实例,并用 class
的 importer
填充它们。如何在大量文件上重复此过程?例如使用 listdir
从文件夹导入所有文件?
我虽然是这样创建实例的:
for i in 'abcd':
eval('%s=RS()' %(i))
但当然似乎不起作用..
最佳答案
您不应该将它们读入具有不同名称的变量中——您将如何使用这些变量?
相反,将它们读入具有单个名称的数据结构。
让我们把创建实例并导入到函数中的实际过程:
def read_instance(filename):
instance = RS()
instance.importer(filename)
return instance
然后你可以列一个 list :
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'
关于python - 如何以编程方式在 Python 中添加实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20999571/