Write multiple dataframes to separate .csv file in a for loop

Viewed 624

I am new to python. I am sure there is simple way to do this but I am struggling a bit. I have 100 dataframes with names Lens1,Lens2, ..., Lens100. I want to write each dataframe to a csv file.

Lens1.to_csv(path+"lens 1.csv", index=False) This command for Lens2 and Lens2.csv... and so on till Lens100 save as Lens100.csv. so a 100 times...

I have tried the following:

for key,j in range(101):
    x='Lens%s'%(j)
    x.to_csv(path+x+".csv")

It does not seem to work and the error is

'str' object has no attribute 'to_csv'.

Any help will be much appreciated.

1 Answers

You are getting this error because the x in your for loop are not dataframes, but strings. You cannot call a dataframe by adding a str to its name; Python will consider it as a string.

You can store the dataframes in a list dataframes first, then store the names of the dataframes in a list name. Then, proceed using the following codes.

for j in range(101):
    x = dataframes[j]
    x.to_csv(path + name[j] + ".csv", index = False)
Related