0

I want to create multiple pandas data frames df1,df2,df3,... from multiple files file1.xlsx, file2.xlsx ... using for loop

filenames = {'file1.xlsx','file2.xlsx','file3.xlsx','file4.xlsx','file5.xlsx'}

for i in range(len(filenames)):
    df+str(i) = pd.read.excel(filenames[i])

and get the syntax error 'can't assign to operator' how can I solve this problem?

0

2 Answers 2

1

Try locals but not recommend

filenames = {'file1.xlsx','file2.xlsx','file3.xlsx','file4.xlsx','file5.xlsx'}
variables = locals()
for i in range(len(filenames)):
   variables["df{0}".format(i)]  = pd.read.excel(filenames[i])

We usually save it into dict

filenames = {'file1.xlsx','file2.xlsx','file3.xlsx','file4.xlsx','file5.xlsx'}
d={'df'+str(i) :  pd.read.excel(filenames[i]) for i in range(len(filenames))}
Sign up to request clarification or add additional context in comments.

Comments

0

Could you try something like this? Use exec to assign the value to the variable?

filenames = ['file1.xlsx','file2.xlsx','file3.xlsx','file4.xlsx','file5.xlsx']

for fname in filenames:
    dfname = fname.split('.')[0]
    df = pd.read_excel(fname)
    exec("%s=%s" % (dfname , df))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.