0

I'm trying to write all the currently available pandas dataframe in workspace to excel sheets. By following example from this SO thead, but I'm unable to make it work.

This is my not working code:

alldfs = {var: eval(var) for var in dir() if isinstance(eval(var), pd.core.frame.DataFrame)}
for df in alldfs.values():
    print(df.name)
    fmane = df+".xlsx"
    writer = pd.ExcelWriter(fmane)
    df.to_excel(writer)
    writer.save()

Any help on how to correct this, so that I can pass the dataframe names to a variable, so that the excel filename being written can be same as the dataframe. I'm using spyder 4, python 3.8

Frash
  • 724
  • 1
  • 10
  • 19
  • `'DataFrame' object has no attribute 'name'` <-- this is the error I get, you should iterate through the keys and values from the dict you are creating in the first line and use the keys as a name. Check out my answer. – Mateusz Dorobek Jun 09 '21 at 14:40

1 Answers1

1

Just a small fix will do the job:

alldfs = {var: eval(var) for var in dir() if isinstance(eval(var), pd.core.frame.DataFrame)}
for df_name, df in alldfs.items():
    print(df_name)
    fmane = df_name+".xlsx"
    writer = pd.ExcelWriter(fmane)
    df.to_excel(writer)
    writer.save()
Mateusz Dorobek
  • 702
  • 1
  • 6
  • 22