How to read EXCEL files in for-loop with python?

Viewed 57

I am a beginner of Python.
Now, I have files "Pref1" and "Pref2".
I would like to read files and define data frame's names with for-loop fuction (there are so many files).
I tried below.

for i in [1,2]:
    f"df{i} = pd.read_excel('Pref{i}.xlsx', sheet_name= 'Sheet2').dropna(axis=0)

However, codes do not work. If you have good ideas, please tell me. Thank you.

1 Answers

Use a dictionary to save your data frames with preferred names and get them later

CODE

import pandas as pd

df_dict = {}

for i in [1, 2]:
    df_dict["df"+str(i)] = pd.read_excel(f'Pref{i}.xlsx', sheet_name='Sheet2').dropna(axis=0)

df1 = df_dict["df1"]
df2 = df_dict["df2"]
Related