Skip to content

Instantly share code, notes, and snippets.

@iris9112
Created December 28, 2022 03:07
Show Gist options
  • Save iris9112/e8af30f46d8cd12b1d3b87125b6d8558 to your computer and use it in GitHub Desktop.
Save iris9112/e8af30f46d8cd12b1d3b87125b6d8558 to your computer and use it in GitHub Desktop.
Three examples of creating nested folders
def method_one():
"""
Method-1: Using pathlib.Path.mkdir()
mkdir(mode=0o777, parents=False, exist_ok=False)
These parameters are optional.
If mode is given, it determines the file mode and access flags.
However, if the path already exists, then it will raise a FileExistsError exception.
If the parameter exist_ok is true, FileExistsError exceptions will be ignored,
but only if the last path component is not an existing non-directory file. (must be a directory?)
Otherwise, it will raise a FileExistsError exception.
If parents=True the directory hierarchy is created
"""
from pathlib import Path
# /home/isabel.ruiz/.config/JetBrains/PyCharm2022.3/scratches/nested_files/new
path = Path("../nested_files/method_one/main/files")
path.mkdir(parents=True, exist_ok=True)
print("First directory structure created successfully.")
def method_two():
"""
Method-2: Using os.makedirs()
It is provided under Python’s standard utility modules.
os.makedirs(name, mode, exist_ok=False)
The makedirs() is a recursive directory creation function like mkdir()
but also makes all intermediate directory to contain the leaf directory.
If intermediate directories are not present then mkdir() throws a FileNotFoundError exception.
Also, If the parameter exist_ok is true, FileExistsError exceptions will be ignored
"""
import os
path = "../nested_files/method_two/main/files"
os.makedirs(path, exist_ok=True)
print("Second directory structure created successfully.")
def method_three():
"""
Method-3: Using distutils.dir_util
The mkpath() function is used to create a directory and any missing parent directories.
If the directory already exists then do nothing.
However, if it is unable to create any directory structure on the way, it will raise DistutilsFileError.
distutils.dir_util.mkpath(name,[mode, verbose=0])
If verbose is true, then it will print a one-line summary of each mkdir to stdout.
This function will return the list of directories actually created.
"""
import distutils.dir_util
path = "../nested_files/method_three/main/files"
distutils.dir_util.mkpath(path, verbose=1)
print("Third directory structure created successfully.")
if __name__ == '__main__':
method_one()
method_two()
method_three()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment