0

Problem:

I am trying to load csv-files from a directory to my workspace. There are a lot of files in the directory containing important information in the filename. I want to load each csv-file and save it to a variable name containing the most important information of the filename.

Approach:

My approach have been to load them locally, loading these variables in a class don't work though. I have read that defining variables that way locals[filename] is bad practice, but I haven't found an easier method to reach my goal than this first 'works as intended'-code block below.

This thread use loops to define their variables: How do you create different variable names while in a loop? But I would like to name them after (parts of) my files I load from a directory.

My code:

import os 

The following code successfully load all files with their filename into the workspace.

works as intended:

directory = C:\Users\...
file_ending = '.csv'

for file in os.listdir(directory):
  if file.endswith(file_ending):
    filename = file[0:3]
    locals()[filename] = pd.read_csv(file,index_col=0)

The following code don't load the files to the workspace.

don't work as intended:

class foo()

  def bar():

    directory = C:\Users\...
    file_ending = '.csv'

    for file in os.listdir(directory):
      if file.endswith(file_ending):
        filename = file[0:3]
        locals()[filename] = pd.read_csv(file,index_col=0)

foo = Foo()
foo.bar()

Other approach:

Another idea would be to load the filenames into a list, do pd.read_csv() on it, save them somehow to a variable name and return the list

files = [file for file in os.listdir(directory) if file.endswith(file_ending)]

but I don't know how to proceed from here explicitly.

lmixa
  • 7
  • 2

0 Answers0