0

I had previously written a script which contained a function for converting a dataframe to .csv and storing it locally, and it had worked in the past, but now i've come to use it again and it will not work:

def write_to_csv(dataframe, filename):
    timestamp = datetime.utcnow().isoformat()
    dataframe.to_csv(fr'C:/Users/freddie.bazanye-lutu/BBDS_Repo/Scripts/{filename}-{timestamp}.csv', index=False, header=True) 

Everytime I run it produces this error:

OSError: [Errno 22] Invalid argument: 'C:/Users/freddie.bazanye-lutu/BBDS_Repo/Scripts/Sandbox_glue_catalog-2021-10-08T10:56:27.991570.csv'

I've tried changing the directions of the slashes, I've updated pandas to the latest version and I've tried changing the location of where i want my file to be saved, all to no avail

FreddieBL
  • 17
  • 1
  • 6
  • colon in the filename might be a problem – Revuimar Oct 08 '21 at 11:24
  • Formatting paths manually is quite nasty. I suggest using [`pathlib`](https://docs.python.org/3/library/pathlib.html) to perform path generation as this module provides quite handy functions. However, I think that your slashes might be the problem as you do have a raw string and need to escape the slashes. – albert Oct 08 '21 at 11:25
  • @Revuimar removed the timestamp which contained the extra colons and it worked, but why was that an issue as I need to use this script in future and the files will need to have timestamps – FreddieBL Oct 08 '21 at 11:43
  • See this answer about [illegal windows filename characters](https://stackoverflow.com/a/31976060/1322401). This is not a python thing, it's a Windows thing. – Steven Rumbalski Oct 08 '21 at 11:51
  • [This is the issue](https://stackoverflow.com/a/25896961/9354135). Colon is one of the forbidden characters in file naming convention. Try to reformat your timestamp - datetime.now().strftime("%Y%M%d-%H%M%S") – Revuimar Oct 08 '21 at 12:00

0 Answers0