Home > Net >  How to write a for loop to read in excel files into Python
How to write a for loop to read in excel files into Python

Time:04-26

I have 10 excel workbooks (data1.xlsx ~ data10.xlsx), each of which has multiple sheets. I'd like to write a for loop to read in Q4 tabs for each workbook so that I don't have to write repeating codes like what I have below.

data1 = pd.read_excel("data1.xlsx", sheet_name = 'Q4')
data2 = pd.read_excel("data2.xlsx", sheet_name = 'Q4')
.
.
.
data9 = pd.read_excel("data9.xlsx", sheet_name = 'Q4')
data10 = pd.read_excel("data10.xlsx", sheet_name = 'Q4')

I want the result of each loop to be assigned to a dataframe name (e.g. data1, data2, etc.) I've tried the following, but it only gave me one output and was assigned under df_name, not data1 or data2...

files = []
filepath = 'C:/Projects/data'
for i in range(1,11):
    df_name = 'data'   str(i)
    df_name = pd.read_excel(filepath str(i) '.xlsx', 'Q4')
    

CodePudding user response:

I suggest using a dictionary to store your DataFrames:

files = {f"data{i}": pd.read_excel(f"{filepath}{i}.xlsx", sheet_name="Q4") for i in range(1,11)}

Then you can access data1 by files['data1'], etc.

  • Related