Create a bunch of objects from files in a directory

323 Views Asked by At

I have made a class that I'm using to manipulate and work with my data.

class DataSet():
    def __init__(self, path, label_names, ohe_names, random_state=420):
        self.df = pd.read_csv(path)
        self.random_state = random_state
        self.encodings = LabelEncoder() 
        self.scaler = StandardScaler()

and I want to create a new DataSet object for each file in a directory with the name of the DataSet being the file name.

I have this code so far.

for file in os.listdir('data/'):
    name = file[:-4]
    path = 'data/'+file

Every name, for example 'fox', should be a new DataSet object with the name name/fox. How can I manage to do this?

Hope this makes sense. Thanks in advance.

2

There are 2 best solutions below

1
On BEST ANSWER

Given that you were happy with your own answer, you should also think about storing your DataSet instances in a container. I'm suggesting a dict:

frames = {}
for file in os.listdir('data/'):
    name = file[:-4]
    path = 'data/'+file
    frames[name] = DataSet(path)
print(frames)
5
On

I managed to figure it out.

for file in os.listdir('data/'):
    name = file[:-4]
    path = 'data/'+file
    exec("{} = DataSet('{}')".format(name, path))