如何创建目录及缺失的父目录

如何创建目录及缺失的父目录

技术背景

在Python编程中,经常会遇到需要创建目录的场景,尤其是需要创建包含缺失父目录的情况。不同版本的Python提供了不同的方法来实现这一功能,下面将详细介绍。

实现步骤

Python 3.5+

使用pathlib.Path.mkdir方法,该方法可以递归创建目录,并且如果目录已存在不会抛出异常。

1
2
from pathlib import Path
Path("/my/directory").mkdir(parents=True, exist_ok=True)

Python 3.2+

使用pathlib

如果可以,安装当前的pathlib的向后兼容包pathlib2。使用方法同Python 3.5+。

使用os

1
2
import os
os.makedirs(path, exist_ok=True)

Python 2.7+

使用pathlib

安装pathlib2,使用方法同Python 3.5+。

使用os

1
2
3
4
5
6
import os
try:
os.makedirs(path)
except OSError:
if not os.path.isdir(path):
raise

替代方法

使用distutils.dir_util.mkpath,该方法可以创建嵌套目录,如果目录已存在则不做任何操作。但需要注意的是,distutils模块已被弃用,计划在Python 3.12中移除。

1
2
import distutils.dir_util
distutils.dir_util.mkpath(path)

核心代码

处理文件路径并创建目录

1
2
3
4
from pathlib import Path
path_to_file = Path("zero/or/more/directories/file.ext")
parent_directory_of_file = path_to_file.parent
parent_directory_of_file.mkdir(parents=True, exist_ok=True)

捕获OSError并检查错误码

1
2
3
4
5
6
7
import os, errno

try:
os.makedirs(directory)
except OSError as e:
if e.errno != errno.EEXIST:
raise

最佳实践

使用pathlib模块

在Python 3.5及以上版本中,推荐使用pathlib模块,它提供了更面向对象的路径操作方式,代码更简洁易读。

1
2
from pathlib import Path
Path("path/to/directory").mkdir(parents=True, exist_ok=True)

处理文件读写时创建目录

1
2
3
4
5
6
7
8
9
10
11
12
13
import os
import errno
filepath = '/my/directory/filename.txt'
directory = os.path.dirname(filepath)
try:
if not os.path.exists(directory):
os.makedirs(directory)
except OSError as error:
if error.errno != errno.EEXIST:
raise
with open(filepath, 'w') as my_file:
# 处理文件内容
pass

常见问题

竞态条件

在使用os.path.existsos.makedirs时,可能会存在竞态条件。例如,在检查目录是否存在后,另一个进程可能会在创建目录之前将其删除。可以通过捕获OSError并检查错误码来避免这种情况。

distutils模块弃用

distutils.dir_util.mkpath虽然可以在Python 2和3中使用,但由于distutils模块已被弃用,不建议在新的项目中使用。

路径问题

在使用os.makedirspathlib.Path.mkdir时,要确保路径格式正确,避免出现路径不存在或路径为文件的情况。如果路径中的子目录与现有文件同名,可能会抛出NotADirectoryError


如何创建目录及缺失的父目录
https://119291.xyz/posts/2025-05-07.how-to-create-directory-and-missing-parent-directories/
作者
ww
发布于
2025年5月7日
许可协议