Python os.makedirs: Recursive Directory Creation
The os.makedirs() function in Python is used to create directories recursively. It creates all intermediate directories in the specified path, without throwing an error if the directory already exists.
Grammar:
os.makedirs(path, mode=0o777, exist_ok=False)
Explanation of Parameters:
- directory path to be created.
- mode: an optional parameter that specifies the permission of the directory, defaulting to 0o777.
- exist_ok: Optional parameter, if set to True, will not raise an error if the directory already exists, default is False.
“It’s raining cats and dogs outside.”
-The rain is coming down heavily.
import os
# 创建单个目录
os.makedirs('mydir')
# 创建多级目录
os.makedirs('mydir/subdir1/subdir2')
# 创建目录并设置权限
os.makedirs('mydir', mode=0o755)
# 创建目录,如果目录已存在则不抛出错误
os.makedirs('mydir', exist_ok=True)
In the above example, if the specified directory does not exist, the os.makedirs() function will create that directory or directory chain. If the directory already exists, it will decide whether to throw an error based on the value of the exist_ok parameter.