1

I have a few csv files in same folder an I need to add them to different dataframes of the same name. I am using the below code

for file in files:
file_name = file.split('.')
if file_name[1] == 'csv':
    file_name[0] = pd.read_csv(file)
else:
    continue

The list of files is ['', 'bond_ratings', 'fund_allocations', 'fund_config', 'fund_ratios', 'fund_specs', 'Hack', 'other_specs', 'return_10year', 'return_3year', 'return_5year']

However, when I try say 'bond_ratings.head()' it says bind_ratings is not defined. Where am I wrong.

1 Answers1

1

You can create dict of DataFrames:

d = {}
for file in files:
    file_name = file.split('.')
    if file_name[1] == 'csv':
        d[file_name[0]] = pd.read_csv(file)

And then select by keys:

print (d['bond_ratings'])

What you need is not recommended, but possible:

for file in files:
    file_name = file.split('.')
    if file_name[1] == 'csv':
        globals()[file_name[0]] = pd.read_csv(file)

print (bond_ratings)
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252