Directory name error when creating dir in python out of the blue

Question:

So i am using a method i made to save some plots of data, and i have automated the process by saving the plots in a sub folder in my current working directory, that has the name of the first and last dates of the data i am doing the plots for.

I have been using said function normally with no problem except one folder (yes only one) with data, gives me an error related to the name of the directory being created as it being incorrect

OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: ‘C:UserstigerDocumentsRadiator_Testvalve_3_512.08.2022_21:00-12.12.2022_04:00_dir’

the string created to be used to make the dir is this:

C:UserstigerDocumentsRadiator_Testvalve_3_512.08.2022_21:00-12.12.2022_04:00_dir

which i have already in the past made successfully files that have this name already and at the same time on other data folders i use the same method with the same format of the name and it works normally

folder with already made directories that of the past, i add manually at the end of every subdirs name the averaging time i used just to be clear with the names are a little bit different

the part of the code that is responsible for the directory creation is this:

first_date, last_date = hfc.help_func.first_last_date(data)

directory = os.getcwd()
directory = os.path.join(directory,first_date + '-' + last_date + '_' +  'dir')
isExist = os.path.exists(directory)
subdir = first_date + '-' + last_date + '_' +  'dir'
if not isExist:
    # Create a new directory because it does not exist
    os.makedirs(directory)

I have tried looking at other methods i use and work normally and they identical to this one that doesn’t work. Mind you it used to work fine and randomly without changing that part of the code it doesn’t

If more details are required or parts of the code please let me know I will provide them

Asked By: joyless_69

||

Answers:

If you are using windows, then using : as part of the directory name is not valid, for example, when manually renaming a folder with : you would get:
enter image description here

Therefore, simply consider replacing the : values for _ or - as you have been regularly doing.

Simply using this should suffice:

first_date, last_date = [x.replace(":","") for x in hfc.help_func.first_last_date(data)]
Answered By: Celius Stingher
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.