Python使用mkdir带parents和exist_ok参数时无法创建最终目录问题
目录创建失败问题修复方案
问题根因
你的代码调用os.makedirs时传入了os.path.dirname(targetpath),该函数会返回目标路径的父级目录:例如当targetpath为/usr/home/jim/DCIM/dir1时,os.path.dirname(targetpath)返回的是/usr/home/jim/DCIM,因此代码实际仅创建到DCIM层级,不会生成最末级的dir1~dir4目录。
修复方案
方案1:保留原有逻辑仅修改参数
删除os.makedirs外层的os.path.dirname调用即可,同时os.makedirs的exist_ok=True参数已兼容目录已存在的场景,可以删掉冗余的存在性判断:
for row in rows: localfile = row[0] fileloc = row[1] # 跳过空条目 if not localfile or not fileloc: continue path = Path(fileloc) mkpath = path.parent.absolute() targetpath = os.path.join(os.environ.get("HOME"), mkpath) print(f"Creating {targetpath}") os.makedirs(targetpath, 0o755, exist_ok=True)
方案2:统一使用pathlib逻辑(更推荐)
你已经引入了pathlib模块,无需混用os.path接口,全pathlib写法更简洁,也能避免路径层级计算错误:
from pathlib import Path home_path = Path.home() for row in rows: localfile = row[0] fileloc = row[1] if not localfile or not fileloc: continue target_path = home_path / Path(fileloc).parent print(f"Creating {target_path}") target_path.mkdir(parents=True, exist_ok=True, mode=0o755)
内容的提问来源于stack exchange,提问作者learningdev001
相关产品推荐
相关产品推荐

