在 Python 中,os.makedirs() 函数用于递归地创建目录。也就是说,它不仅会创建指定的目录,还会创建任何必要的父目录。这个函数在处理需要创建多级目录结构时非常有用。
1 2 3 4 5 |
import os # 创建单级目录 os.makedirs('test_dir') # 创建多级目录 os.makedirs('parent_dir/child_dir/grandchild_dir') |
1 2 3 |
import os # 创建目录并设置权限为 0o755 os.makedirs('secure_dir', mode=0o755) |
1 2 3 |
import os # 创建目录,如果目录已存在则不会引发异常 os.makedirs('existing_dir', exist_ok=True) |
如果目标目录已经存在且 exist_ok 参数为 False,会引发 FileExistsError 异常:
1 2 3 4 5 |
import os try: os.makedirs('existing_dir') except FileExistsError: print("Directory already exists") |
os.makedirs() 函数在需要确保目录结构存在时非常有用,例如在文件写入操作之前:
1 2 3 4 5 6 7 8 9 10 11 |
import os def save_file(file_path, content): # 提取目录路径 dir_path = os.path.dirname(file_path) # 创建目录(如果不存在) os.makedirs(dir_path, exist_ok=True) # 写入文件 with open(file_path, 'w') as file: file.write(content) # 使用示例 save_file('data/output/file.txt', 'Hello, world!') |
通过使用 os.makedirs() 函数,可以方便地创建所需的目录结构,从而避免手动检查和创建目录的繁琐过程,提高代码的简洁性和可维护性。