Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading multiple files into separate data frames in PYTHON

I want to know if there's a way in python for reading multiple CSV file form a folder and assigning to separate data frame by the name of the file. The below code will throw an error but to show the point I pasted it

import glob
for filename in glob.glob('*.csv'):
    index = filename.find(".csv")
    if "test" in filename:
        filename[:index]) = pd.read_csv(filename)
like image 807
Guna pandian Avatar asked Mar 22 '26 13:03

Guna pandian


1 Answers

I believe you need create dictionary of DataFrame with keys by filenames:

d = {}
for filename in glob.glob('*.csv'):
    if "test" in filename:
        d[filename[:-4]] = pd.read_csv(filename)

What is same as:

d = {f[:-4]: pd.read_csv(f) for f in glob.glob('*.csv') if "test" in f}

If want only name of file is possible use:

d = {os.path.basename(f).split('.')[0]:pd.read_csv(f) for f in glob.glob('*.csv') if "test" in f}
like image 73
jezrael Avatar answered Mar 24 '26 22:03

jezrael



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!