I have a class to import data from a CSV file, and a function that takes the filename and a name for the output list. I want to set the name of the self.data_name to be self.info using the setattr() function. How can I do this?
import csv
class import_data:
def import_csv(self, filename_csv, data_name):
setattr(self,data_name,0)
datafile = ope开发者_开发问答n(filename_csv, 'r')
datareader = csv.reader(datafile)
self.data_name = []
for row in datareader:
self.data_name.append(row)
print("finished importing data")
b = import_data()
b.import_csv('info.csv', 'info')
print(b.info)
This does not work because b.data_name is not b.info. This prints 0 instead of the imported CSV file.
Try this:
class import_data:
def import_csv(self, filename_csv, data_name):
with open(filename_csv, 'r') as f:
setattr(self, data_name, list(csv.reader(f)))
print("finished importing data")
You're going to have to replace all usages of self.data_name in the import_csv() function with calls to either setattr() or getattr() to be able to use the dynamic name.
Using self.data_name will use the member named data_name, as I suspect you've already realised, and that isn't what you want to do.
For example, try the following:
class import_data:
def import_csv(self, filename_csv, data_name):
#set dynamic named item to default value
#not required if this will happen anyway (in this example it does)
setattr(self,data_name,[])
#preparation activities
datafile = open(filename_csv, 'r')
datareader = csv.reader(datafile)
#do required work using a temporary local variable
temp = []
for row in datareader:
temp.append(row)
#copy the temporary local variable into the dynamically named one
setattr(self, data_name, temp)
#tidy up activities
datafile.close()
print("finished importing data")
Make sure you take a look at eumiro's answer, which takes a better, more compact and more Pythonic approach to your specific problem using with and list(). However, the above should hopefully make it clear how you could be using setattr() in a wider variety of cases.
加载中,请稍侯......
精彩评论