0

how can I iterate over .csv files in a folder, create dataframe from each .csv and name those dateframes after respective .csv files. Or it could be actually any other name.

My approach doesnt event create a single dataframe.

path = "/user/Home/Data/"

files = os.listdir(path) 

os.chdir(path)

for file, j in zip(files, range(len(files))):
     if file.endswith('.csv'):
        files[j] = pd.read_csv(file)

Thanks!

Yaahtzeck
  • 217
  • 2
  • 13
  • have you tried using glob? this [post](https://stackoverflow.com/questions/20906474/import-multiple-csv-files-into-pandas-and-concatenate-into-one-dataframe) might help with what you're trying to do – jtitusj Dec 09 '20 at 01:47
  • if you want to access dataframes by name, consider adding them to a dictionary. FWIW you can use `for index, filename in enumerate(files)`. – jkr Dec 09 '20 at 01:50

1 Answers1

0

You can use pathlib and a dictionary to do that (as already pointed out by jitusj in the comment).

from pathlib import Path

path = Path(".../user/Home/Data/") # complete path needed! Replace "..." with full path

dict_of_df = {}
for file in path.glob('*.csv'):
    dict_of_df[file.stem] = pd.read_csv(file)

Now you have a dictionary of dataframes, with the filenames as keys (without .csv extension).

above_c_level
  • 3,579
  • 3
  • 22
  • 37