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 = open(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.
You’re going to have to replace all usages of
self.data_namein theimport_csv()function with calls to eithersetattr()orgetattr()to be able to use the dynamic name.Using
self.data_namewill use the member nameddata_name, as I suspect you’ve already realised, and that isn’t what you want to do.For example, try the following:
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
withandlist(). However, the above should hopefully make it clear how you could be usingsetattr()in a wider variety of cases.