4 Different Ways to mkdir in Python
Published on Aug. 22, 2023, 12:14 p.m.
Certainly, here are four different ways to create a directory in Python:
Using os.mkdir() method:
This method is used to create a new directory.
import os
path = "/path/to/directory"
os.mkdir(path)
Using os.makedirs() method:
This method is used to create a nested directory.
import os
path = "/path/to/directory"
os.makedirs(path)
Using Pathlib:
This method involves creating a Path object and then calling the mkdir() method on it.
from pathlib import Path
path = Path("/path/to/directory")
path.mkdir(parents=True, exist_ok=True)
Using subprocess.call() method:
This method involves calling the mkdir command with the help of subprocess.
import subprocess
path = "/path/to/directory"
subprocess.call(['mkdir', '-p', path])
Note that different methods may be more appropriate for different situations, depending on the specifics of your use case.