pythonos.path

Naming a new folder path based on formula


I am trying to create new folders based on the date. How can I use the below code to add a date or specific string to a folder path to make the new file named as such?

MonthNum = pd.to_datetime('today').strftime('%m.')
MonthName = pd.to_datetime('today').month_name()
Year = pd.to_datetime('today').strftime(' %Y')
FolderName = (MonthNum+MonthName+Year)

    if not os.path.exists(r'C:\Users\Test\'+FolderName):
        os.makedirs(r'C:\Users\Test\'+FolderName)

Solution

  • # using datetime
    dt = datetime.now()
    folderName = f"{dt.month}-{dt.strftime('%B')}-{dt.year}"
    
    # using pandas
    dt = pd.to_datetime('today')
    folderName = f"{dt.month}-{dt.month_name()}-{dt.year}"
    
    
    abspath = os.getcwd() # current dir or wherever you want to create a it
    folder = os.path.join(abspath, folderName)
    if not os.path.exists(folder):
        os.makedirs(folder)
    

    enter image description here