pythonpython-object

Create a bunch of objects from files in a directory


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.


Solution

  • 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)