1

I have a lot dataframes ( created in previous script) all starts with P20 (names). They Are not save in aby folders, just as variables in script. I need to select those dataframes And convert to excel with same name. Ie

For each dataframe.name like  (P20*)
Dataframes.to_excel(dataframe.nale.xlsx)`

I assume i need to use some global function but i am not familiar with that. Can you please help me with that? Thank you

Winter
  • 87
  • 9
  • what did you try? Do you know `os.listdir()` and later `if filename.startswith("P20"): ...`. OR `glob.glob("P20*")` ? – furas Apr 04 '22 at 12:22
  • If you're talking about in-memory dataframes: https://stackoverflow.com/questions/41113663/pandas-get-a-list-of-all-data-frames-loaded-into-memory – gangabass Apr 05 '22 at 05:06

1 Answers1

0

One method is to use os.listdir() and .startswith()

for filename in os.listdir(folder):
    if filename.startswith("P20"):

       old_path = os.path.join(folder, filename)

       df = pd.read_csv(old_path)

       #new_path = old_path.replace(".csv", ".xlsx")
       new_path = old_path + ".xlsx"

       df.to_excel( new_path )

Other method is glob.glob()

for old_path in glob.glob(folder + "/P20*"):

    df = pd.read_csv(old_path)

    #new_path = old_path.replace(".csv", ".xlsx")
    new_path = old_path + ".xlsx"

    df.to_excel( new_path )
furas
  • 134,197
  • 12
  • 106
  • 148