Search code examples
pythonpandasexport-to-csv

Saving each dataframe from a list to separate csv files


Im trying to save each element from a list to each separate csv files. each element is a dataframe.

I used the following codes, however, the problem is that the files that it saves are only from the first or last element of the list from the two following codes respectively. e.g. the output files are all identical

for x in allcity:
    for a in range(0,20):
        x.to_csv('msd{}.csv'.format(a))

for a in range(0,20):
    for x in allcity:
        x.to_csv('msd{}.csv'.format(a))

Solution

  • The problem is that the nested loop will write the last data frame from the allcity list to the range of values in both cases. You have two options:

    counter = 0
    for x in allcity:
        x.to_csv('msd{}.csv'.format(counter)
        counter += 1
    

    or

    for (counter, x) in enumerate(allcity):
        x.to_csv('msd{}.csv'.format(counter)