Bootstrap FreeKB - Python (Scripting) - Create directory using os.mkdir
Python (Scripting) - Create directory using os.mkdir

Updated:   |  Python (Scripting) articles

There are two similar Python modules that can be used to create a directory.

The main difference between these modules is that os.mkdir will not create parent directories and will raise an exception if parent directories do not exist. os.makedirs will create parent directories if they do not exist.

Here is the minimal boilterplate code without try/except/else error handling to create the /usr/local/foo directory using os.mkdir.

#!/usr/bin/python3
import os
os.mkdir("/usr/local/foo")

 

Here is a more practical example, with try/except/else error handling.

#!/usr/bin/python3
import os

directory = "/usr/local/foo"

if os.path.exists(directory ):
  print(f"{directory} already exists")
else:
  try:
    os.mkdir(directory)
  except Exception as exception:
    print(f"got the following exception when attempting to mkdir {directory} - {exception}")
  else:
    print(f"successfully created directory {directory}")

 

Optionally, the directory permissions can be included (0770 in this example).

#!/usr/bin/python3
import os

directory = "/usr/local/foo"

if os.path.exists(directory ):
  print(f"{directory} already exists")
else:
  try:
    os.mkdir(directory, 0o770)
  except Exception as exception:
    print(f"got the following exception when attempting to mkdir {directory} - {exception}")
  else:
    print(f"successfully created directory {directory}")

 

But some systems ignore the mode (e.g. 0o770) include in os.mkdir and os.makedirs so, for stability, I almost always use os.chmod if I need to update the directory to have certain permissions.

#!/usr/bin/python3
import os

directory = "/usr/local/foo"

if os.path.exists(directory):
  print(f"{directory} already exists")
else:
  try:
    os.mkdir(directory)
  except Exception as exception:
    print(f"got the following exception when attempting to mkdir {directory} - {exception}")
  else:
    print(f"successfully created directory {directory}")

    try:
      os.chmod(directory, 0o770)
    except Exception as exception:
      print(f"Got the following exception when attempting to update {directory} to mode -rwxrwxr-x (0775) - {exception}")
    else:
      print(f"Successfully updated {directory} to mode -rwxrwxr-x (0775)")

 

Be aware that if you try to create a directory and the parent directories do not exist, an exception will be raised. For example, if /usr/local/foo does not exist and you try to create /usr/local/foo/bar, an exception will be raised. For this reason, I almost always use os.makedirs instead of os.makedir.

#!/usr/bin/python3
import os

directory = "/usr/local/foo/bar"

if os.path.exists(directory ):
  print(f"{directory} already exists")
else:
  try:
    os.mkdir(directory, 0o770)
  except Exception as exception:
    print(f"got the following exception when attempting to mkdir {directory} - {exception}")
  else:
    print(f"successfully created directory {directory}")

 

Be aware that if the user attempting to create the directory does not have permission to create the directory, then "permission denied" should be returned. For example, let's say /usr/local is owned by root.

~]$ ls -ld /usr/local
drwxr-xr-x. 18 root root 219 Apr 28 05:36 /usr/local

 

If the user attempting to create the directory has sudo permission to create the directory, they instead of using os.makedirs or os.mkdir, it may make more sense to go with os.system.

#!/usr/bin/python3
import os
os.system(f"sudo mkdir --parents /usr/local/foo")

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter e52d61 in the box below so that we can be sure you are a human.