beridzeg45
beridzeg45

Reputation: 416

create dataframes with different names with pd. read_csv and for loop

import pandas as pd
import os
path=r"C:\Users\berid\OneDrive\Desktop\mydata\covid19 South Korea\\"
for file in os.listdir(path):
    print(file)

output:

enter image description here

I want to create dataframes with the same names as csv files.

for file in os.listdir(path):
    name=file.split(".csv")[0]
    name=pd.read_csv(path+file)

This creates dataframe with the name "name". I want dataframes names to be "Case","PatientInfo","Policy",etc.

Upvotes: 1

Views: 338

Answers (2)

Redox
Redox

Reputation: 9967

this should help create the dataframes...

for file in os.listdir(path):
    name=file.split(".csv")[0]
    exec('{} = pd.read_csv(\'{}\')'.format(name, file))

Upvotes: 1

keramat
keramat

Reputation: 4543

Use:

for file in os.listdir(path):
    name=file.split(".csv")[0]
    df=pd.read_csv(path+file)
    exec("%s = df" % (name))

Demonstration:

name = 'ali'
df = pd.DataFrame([1,2,3])
exec("%s = df" % (name))

Output:

ali

    0
0   1
1   2
2   3

Upvotes: 1

Related Questions