Saketh Garuda
Saketh Garuda

Reputation: 79

Read multiple csv's and concat to multiple dataframes based on filenames python

I have a list of csv's with the same columns. Here is how the list looks like,

C:/Users/foo/bar/January01.csv
C:/Users/foo/bar/February01.csv
C:/Users/foo/bar/March01.csv
C:/Users/foo/bar/January02.csv
C:/Users/foo/bar/March02.csv

I want something like this, all csv's that start with January should copy the data into January dataframe and likewise for all months.

Can anyone help me on this?

Upvotes: 0

Views: 28

Answers (1)

Bruno Mello
Bruno Mello

Reputation: 4628

You can first iterate trough your directory to find all months you have, then you pass again appending the dataframes and finally saves them:

import os
dir_name = #your dir
months = set()
for file in os.listdir(dir_name):
    months.add(file[:-2])

month_df = {month: pd.DataFrame() for month in months}
for file in os.listdir(dir_name):
    month_df[file[:-2]] = month[file[:-2]].append(pd.read_csv(os.join.path(dir_name, file)))

for month in month_df.keys():
    month_df[month].to_csv(month + '.csv', index=False)

Upvotes: 2

Related Questions