简体   繁体   中英

use a loop to read and save different files under different dataframes

I have 4 different excel files. I would like to open and save each of them under a variable name of the same name as the excel file with a loop (in python). So I just want to create 4 different pandas dataframes. The step where it keeps getting stuck is when I allocate the name of the dataframe.

files = ["id_2021_05_11",
         "char_2021_05_11",
         "id_2021_05_25",
         "char_2021_05_25"
        ]

for file in files:
    "{}".format(file) = pd.read_excel(r'C:\Users\...\{}.xls'.format(file), index_col=0)

I've seen suggestions to create a list or dictionnary and append each of them into the list/dict. But that's not what I want. I just want 4 dataframes.

Here is a way to do so:


files = ["id_2021_05_11",
         "char_2021_05_11",
         "id_2021_05_25",
         "char_2021_05_25"]

for file in files:
    exec(file + " = pd.read_excel(r'C:\Users\...\{}.xls'.format(file), index_col=0)")

# Check dfs
print(id_2021_05_11.head())
print(char_2021_05_11.head())
print(id_2021_05_25.head())
print(char_2021_05_25.head())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM