0

I'm having trouble setting the name of a dataframe that I'm trying to write to a csv file.

def write_csv(df):
  os.makedirs('Output_csv_files', exist_ok=True)
  df.to_csv(f"{df}.csv")
  return print("Success!")

This is making the contents of the dataframe the name of it rather than the name of the variable itself. For example, if my df's name is "walmart_df," it wouldn't name the csv file "walmart_df.csv" but rather "[whatever the contents of the dataframe are].csv". How can I fix this?

Aaron
  • 113
  • 1
  • 7
  • Thanks for this @Stefan - this is really interesting but I get a syntax error when I try it. Is it possible that it works for dicts but not for dataframes? – Aaron Apr 01 '22 at 15:35
  • how about using `df.name`? – Edo Akse Apr 01 '22 at 15:55
  • Have you tried [this](https://stackoverflow.com/a/58451182/14311263) answer? – Timus Apr 01 '22 at 21:30
  • Thanks for pointing here @Timus, this is really interesting but I get a syntax error when I try it. Is it possible that it works for dicts but not for dataframes? – Aaron Apr 02 '22 at 22:58
  • @Aaron Works for me with dataframes. What kind of syntax error do you get? – Timus Apr 02 '22 at 23:01

0 Answers0