Home » excel » pandas – Save an excel file under several names

pandas – Save an excel file under several names

Posted by: admin May 14, 2020 Leave a comment

Questions:

I have the following list:

File_name_list=['A','B','C','D','E']

I am trying to save an excel file named as each of the elements contained in the list. I’m not sure how to accomplish this. I tried:

for e in File_name_list:
    print (e)
    df.to_excel('C:/Users/user/Desktop/'%File_name_list)

So at the end I want to end up with five different files.

Thank you for your help.

How to&Answers:

When you do a for (a) in (b): loop, (b) describes the list you want to loop through, while (a) describes the element that each iteration of the loop is looking at. In your case, each iteration of the loop looks at either ‘A’ or ‘B’ or ‘C’, and stores that into your variable “e”. To use this variable, all you have to do is:

for e in File_name_list:
    print (e)
    df.to_excel('C:/Users/user/Desktop/'+e)

It’d also be a good idea to append the file type on the end of your file name like so:

df.to_excel('C:/Users/user/Desktop/'+e+'.xls')

Answer:

you can use:

df.to_excel('C:/Users/user/Desktop_/'+e+'_.xlsx')

Or:

df.to_excel('C:/Users/user/Desktop_/{}_.xlsx'.format(str(e)))