How to create a directory in Python?

Question:

How can I use Python to be able to create a certain directory?

For example:

app/
   main.py

How could I create a directory called temp inside the app through Python main.py ?

Answer:

Response using Python 3.*

You can use os.makedirs or os.mkdir .

os.makedirs

Creates all directories that are specified in the parameter, recursively.
E.g.: os.makedir('./temp/2016/12/09') will create the folders temp , 2016 , 12 and 09 .

os.mkdir

It only creates the last directory. If the previous directories do not exist it will cause an error.
E.g.: os.mkdir('./temp/2016/12/09') – it will only create the 09 directory and only if the previous ones exist, otherwise it will cause the following error

FileNotFoundError: [WinError 3] The system cannot find the specified path: './1/2/3/4'


Example:

import os

dir = './temp'       
os.makedirs(dir)
# ou 
os.mkdir(dir)
Scroll to Top