1

I have a list of dataframes (n = 275). I'd like to save each one of them as a separate csv file in the same directory on my PC. I'd like to write a function to do that automaticaly. maybe someone could give an advice how can I do that?

Can anybody assist me in this:

dframes_list - list of dataframe names

df_00001 - dataframe name example that I have now and that I expect.

Thank you in advance.

2 Answers2

3

(does not address OP; leaving here for historical purposes)

You can do something simple by looping over the list and calling the DataFrame.to_csv method:

import os

folderpath = "your/folder/path"
for i, df in enumerate(dframes_list, 1):
    filename = "df_{}".format(i)
    filepath = os.path.join(folderpath, filename)
    df.to_csv(filepath)
CrepeGoat
  • 2,315
  • 20
  • 24
  • That doesn't work ((( : AttributeError: 'str' object has no attribute 'to_csv' – user13311996 Apr 14 '20 at 14:38
  • AH! sorry, I misread the question; you have a list of dataframe *names*. are these filenames? – CrepeGoat Apr 14 '20 at 14:52
  • yes, they are. I've splited data and made a list of all dataframes I actually have now. Now I would like to save each one of them separately. – user13311996 Apr 14 '20 at 15:02
  • so you have a list of filenames, and you want to copy those files from one location to another? Am I understanding this right? Because if that's all you want to do, then there's no reason to even use `pandas`; you can just stick with file manipulations that `os` and `sys` make available to you. If that's correct let me know and I'll write up another answer. – CrepeGoat Apr 14 '20 at 15:05
  • I have 1 big dataframe that was splited to 275 dataframes. They are not saved and are only in the memory of environment. I'd like to save them in my PC memory as separate csv files. I hope I've answered on your question more clearly. – user13311996 Apr 14 '20 at 15:26
  • This is my main point of confusion I think: if `dframes_list` is only the list of the dataframe *names*, then where are the *actual* 275 dataframes? Is there another variable somewhere that stores them? – CrepeGoat Apr 14 '20 at 16:44
2

I think the following code will do what you want. Putting it here for others who may want to create separate dataframes from a list of dataframes in python

This an update to the answer provided by @CrepeGoat

import os

folderpath = "your/folder/path-where-to-save-files"
csv = 'csv'  # output file type
for i, df in enumerate(dflist, 1):
    filename = "df_{}.{}".format(i, csv)
    filepath = os.path.join(folderpath, filename)
    df.to_csv(filepath)
GSA
  • 751
  • 8
  • 12