在创建多级目录时,pathlib.Path.mkdir() 为何会抛出FileNotFoundError?
我在使用 pathlib.Path.mkdir() 来创建一个嵌套的目录结构。我本以为该调用会创建所有缺失的父目录,但它抛出了异常。
最小可复现示例:
python
from pathlib import Path
path = Path('data/output/reports')
path.mkdir()
实际结果:
FileNotFoundError: [Errno 2] No such file or directory: 'data/output/reports'
期望的结果:
目录结构应该会自动创建:
data/
└── output/
└── reports/
运行环境:
- Python 3.12
- Windows 11
为什么在父目录不存在时 Path.mkdir() 会失败,使用 pathlib 创建嵌套目录的推荐方法是什么?
解决方案
请参阅Python的 pathlib文档,你可以使用 path.mkdir(parents=True) 来创建此路径的任何缺失父目录,或者在不在意目标目录是否已存在时使用 path.mkdir(parents=True, exist_ok=True)。
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。