How to create folder in Python

Create folder in Python

To create a folder in python just call os.mkdir. E.g. create file mkfolder.py:

import os
os.mkdir('fol_in_pwd')

This will create a folder in the current PWD.

NOTE: PWD is not folder that contains script, but folder where the process was executed

e.g. if you are located in /home/user/ calling python scripts/mkfolder.py will create /home/user/fol_in_pwd/ but not /home/user/scripts/fol_in_pwd/

NOTE: To check the 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 the absolute path of a 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 an absolute path
import os

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

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

The 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 filter 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):
  os.mkdir(new_abs_path)

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

#python
menu 4
Bruce Hardy profile picture
Oct 22, 2020
by Bruce Hardy
Did it help you?
Yes !
No

Best related

Other by Bruce Hardy