python 生成目录
时间: 2023-07-05 22:31:09 浏览: 97
你可以使用Python的os和os.path模块来生成目录。具体的实现方法如下:
确定目录结构,使用os.path.join()方法连接目录名和文件名。
使用os.makedirs()方法创建目录,如果目录已经存在,则不会创建。
下面是一个例子,演示如何创建一个目录结构:
import os
# 定义目录结构
dir_structure = {
'docs': {
'user_guide': ['introduction.md', 'installation.md', 'usage.md'],
'developer_guide': ['contribution.md', 'development.md']
},
'src': {
'python': ['utils.py', 'config.py'],
'java': ['utils.java', 'config.java']
}
}
# 遍历目录结构创建目录
def make_dirs(path_structure):
for path, contents in path_structure.items():
full_path = os.path.join(os.getcwd(), path)
if not os.path.exists(full_path):
os.makedirs(full_path)
if isinstance(contents, dict):
make_dirs(contents)
else:
for file in contents:
open(os.path.join(full_path, file), 'a').close()
# 创建目录结构
make_dirs(dir_structure)
这个例子会在当前工作目录下创建一个名为“docs”的目录,并在“docs”目录下创建一个名为“user_guide”的子目录,该子目录下包含三个文件:“introduction.md”、“installation.md”和“usage.md”。同时,还会创建一个名为“src”的目录,该目录下包含两个子目录:“python”和“java”,每个子目录下包含两个文件。
相关推荐














