-2

I have several files in a folder. I can list them via from os.listdir(path). Now, I'd like to open those files and name the objects ( pandas DataFrame) after their file names (without extension). Lets say I have files_list=[file1.csv, file2.csv] and now I want to avoid:

file1=pd.read_csv(file1.csv) ... In case I had 100 files the task would be tedious. Instead, I'd like something like for file in files_list: file_name = pd.read_csv(file)

this way I could have something like: ''' file_name_1 object (DataFrame from the file_name_1.csv) file_name_2 object (DataFrame frrom the file_name_2.csv) Any help?

abusiro
  • 23
  • 5
  • 1
    Can you explain it a bit better, I am a bit confused – Josip Juros Apr 07 '22 at 07:52
  • Surely the files are named already? So why do you want to name them again? – Schnitte Apr 07 '22 at 07:53
  • Maybe a duplicate of https://stackoverflow.com/questions/8028708/dynamically-set-local-variable? – DavidW Apr 07 '22 at 07:54
  • You can set global variables dynamically, and you can set attributes of a class instance dynamically, but not local variables within a function. – DavidW Apr 07 '22 at 07:55
  • You'd like something like... It should work fine, once you avoid using `file` twice: `for file in files_list: data = pd.read_csv(file)` would be ok – gimix Apr 07 '22 at 08:05
  • I have edited my post, so that it is more understandable. It is not the files that I want to name. but the DataFrames I get from those files. – abusiro Apr 08 '22 at 09:44

1 Answers1

2

You could use a dictionnary like this:

from os.path import splitext

def rm_ext(filename):
    """Returns the filename without its extension."""
    return splitext(filename)[0]

files = {}
for file in files_list:
   files[rm_ext(file)] = pd.read_csv(file)

You can then access to file1 like so files["file1"].

Raida
  • 1,206
  • 5
  • 17