python
主页 > 脚本 > python >

python makedirs() 递归创建目录介绍

2024-12-14 | 佚名 | 点击:

在 Python 中,os.makedirs() 函数用于递归地创建目录。也就是说,它不仅会创建指定的目录,还会创建任何必要的父目录。这个函数在处理需要创建多级目录结构时非常有用。

1、语法

1.1、参数

1.2、返回值

1.3、示例

1.3.1、基本用法

1

2

3

4

5

import os

# 创建单级目录

os.makedirs('test_dir')

# 创建多级目录

os.makedirs('parent_dir/child_dir/grandchild_dir')

1.3.2、使用 mode 参数

1

2

3

import os

# 创建目录并设置权限为 0o755

os.makedirs('secure_dir', mode=0o755)

1.3.3、使用 exist_ok 参数

1

2

3

import os

# 创建目录,如果目录已存在则不会引发异常

os.makedirs('existing_dir', exist_ok=True)

1.3.4、错误处理

如果目标目录已经存在且 exist_ok 参数为 False,会引发 FileExistsError 异常:

1

2

3

4

5

import os

try:

    os.makedirs('existing_dir')

except FileExistsError:

    print("Directory already exists")

2、实际应用

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() 函数,可以方便地创建所需的目录结构,从而避免手动检查和创建目录的繁琐过程,提高代码的简洁性和可维护性。

原文链接:
相关文章
最新更新