0

I would like to write a function that saves multiple data frames into csv files at once with the file names corresponding to the data frame name. For instance if I have my_data_frame_1= county1_zipcodes I would like to write a function that takes my_data_frame_1 and saves it as my_data_frame_1.csv. So far I have tried the following:

def get_df_name(df):
    name =[x for x in globals() if globals()[x] is df][0]
    return name

def save_df_csv(*args):
    '''
    To save all the data frames into csv files
    '''
    for df in args:
        print (df)
        df_name = get_df_name(df)
        df.to_csv(df_name+'.csv',index=False)
    return

However, this doesn't work. The functions are imported from another script and globals() gives an empty list. I have tried using locals() but that doesn't work either (it gives me df as the data frame name). Any help is appreciated.

MSB
  • 177
  • 2
  • 10
  • Does this answer your question? [Getting the name of a variable as a string](https://stackoverflow.com/questions/18425225/getting-the-name-of-a-variable-as-a-string) – warped Feb 06 '21 at 21:25
  • Where does the dataframe name originally come from? You should create a dict where the key is the name and the value is the dataframe. Then you can use the key to save the file. – Eric Truett Feb 07 '21 at 01:38

0 Answers0