在 Python 中,可以使用 os
模块来实现自动生成目录。具体方法是使用 os.makedirs()
函数,该函数可以创建文件夹。
示例代码如下:
importos
directory = 'path/to/directory'
if not os.path.exists(directory):
os.makedirs(directory)
这段代码首先检查指定的目录是否存在,如果不存在,则使用 os.makedirs()
函数创建该目录。
需要注意的是,如果父目录不存在也会创建,所以是递归创建目录。