Python create folder

To create folder in python just call os.mkdir. E.g. create file

import os

This will create folder in current PWD.

NOTE: PWD is not folder which contains script, but folder where process was executed
e.g. if you are locatedin /home/user/ calling python scripts/ will create /home/user/fol_in_pwd/ but not /home/user/scripts/fol_in_pwd/

NOTE: To check current location in Linux/Mac terminal use pwd, on Windows use cd without arguments

Create a folder in python script folder

To create a folder in python script near the script itself:

  1. Find absolute path of script with os.path.realpath(__file__)
  2. Create an absolute path of a new folder with os.path.join
  3. Call os.mkdir passing formed absolute path
import os

script_path = os.path.realpath(__file__)
new_abs_path = os.path.join(script_path, 'fol_near_script')

Now if you are in /home/user/ calling python scripts/ will create /home/user/scripts/fol_in_pwd/

Safe way in python – create folder if not exists

Just call os.path.exists before actually call create and check returned result – if it returns True, then filder exists and you should do nothing:

import os
import sys

script_path = os.path.realpath(__file__)
new_abs_path = os.path.join(script_path, 'fol_near_script')
if not os.path.exists(new_abs_path):

So now it will create folder only if it does not exist, otherwise you don't have to create a folder at all.

menu 4
Bruce Hardy profile picture
Oct 22, 2020
by Bruce Hardy

Best related

Other by Bruce Hardy