Home > Software engineering >  Errno 22 Invalid argument when trying to export dataframe to excel
Errno 22 Invalid argument when trying to export dataframe to excel

Time:03-03

I'm trying to export my dataframe to excel. My code looks like this:

import os
import pandas as pd

clients_file = pd.read_excel("count.xlsx", engine="openpyxl", header=0)
clients_file.to_excel(os.path.join("path", "backup", "weekly", "12345", "12345"   "_"   pd.datetime.today().strftime('%Y-%m-%d-%H:%M:%S'))   ".xlsx", index=False, sheet_name="report") 

My problem is that I get this error:
OSError: [Errno 22] Invalid argument: 'path\backup\weekly\12345\12345_2022-03-03-12:10:56.xlsx' and I don't know really why. I know that I can use " " to join strings, but path.join is nicer to read. visially Any ideas ? Cheers!

CodePudding user response:

If you are doing this in Windows, : is not allowed as part of a file name. A suggestion:

date_str = pd.datetime.today().strftime('%Y-%m-%d-%H-%M-%S'))
clients_file.to_excel(os.path.join("path", 
                                   "backup", 
                                   "weekly", 
                                   "12345", 
                                   "12345_"   date_str   ".xlsx", 
                      index=False, 
                      sheet_name="report")
  • Related