Python: Add Folder If It Does Not Exist

Posted in Python

Scenario

Maintaining an organized folder structure is important when you are respoible for a growing inventory of data, files, and reports.

Here is how I utilize python to automate the folder directory setup on a monthly basis.

Imports

I'm using the built-in datetime and os.path python packages to set my folder path based on the Year/month.

import datetime
import os.path

Code

To start, I needed to create some variables to extract the year and prior month based on today's date.

So for example, if todays date is September 2, 2019...the below code will set year to 2019 and lastMonth to 08.

After assigning these variables, I'm able to use them to create the filePath variable which will be used to test if the folder path exists or not.

Within an if statement I used 'not os.path.exists()' and passed in the 'filePath' argument (previously created). If this folder path does not exist then it causes the if statement to be True and executes the 'os.makedirs(filePath)' line of code.

today = datetime.date.today()
first = today.replace(day=1)
lastMonth = first - datetime.timedelta(days=1)
year = lastMonth.strftime("%Y")
lastMonth = lastMonth.strftime("%m")

filePath = f"Your\\File\\Path\\{year}\\{lastMonth}"

if not os.path.exists(filePath):
    os.makedirs(filePath)
    print(f"{year}-{lastMonth} file path created")