Python os.makedirs: Create Directories Recursively
The os.makedirs() function in Python is used to create directories recursively. It will raise an OSError if the directory already exists. If the directory is successfully created, it will return None.
The function’s purpose is to create one or multiple directories, including all necessary intermediate directories. In contrast to the os.mkdir() function, this function can create multiple directories at once. For example, to create a directory structure named “dir1/dir2/dir3,” you can use os.makedirs(“dir1/dir2/dir3”).
Here is an example of creating a directory using the os.makedirs() function:
import os
# 创建一个名为"test"的目录
os.makedirs("test")
# 创建一个名为"dir1/dir2/dir3"的目录结构
os.makedirs("dir1/dir2/dir3")
In the examples above, os.makedirs(“test”) created a directory named “test”. os.makedirs(“dir1/dir2/dir3”) created a directory named “dir1”, then created a subdirectory named “dir2” within it, and finally created a subdirectory named “dir3” within “dir2”.