回答

收藏

如何安全地创建嵌套目录?

技术问答 技术问答 617 人阅读 | 0 人回复 | 2023-09-11

检查文件要写的目录是否存在。如果不存在,请使用 Python 创建目录最优雅的方法是什么?这是我试过的:+ D( R( ^; j6 G8 H- T: R$ r
    import osfile_path = "/my/directory/filename.txt"directory = os.path.dirname(file_path)try:    os.stat(directory)except:    os.mkdir(directory)f = file(filename), c  A9 _( L- _" Z& B- |; e
不知何故,我错过了os.path.exists(感谢 kanja、Blair 和 Douglas)。这就是我现在所拥有的:2 {% P+ f8 @7 M2 D/ F
    def ensure_dir(file_path):    directory = os.path.dirname(file_path)    if not os.path.exists(directory):        os.makedirs(directory)6 b; r. R! ?) d: r
是否有标志open()自动发生?' b+ _. u$ m7 a; y. C
                                                                % R( M1 q( T/ a* }# I6 D" b- D
    解决方案:                                                               
9 V; \: M3 `1 A. B) N8 H; ~3 f4 x% f( G                                                                在 Python ≥ 3.5 上,使用pathlib.Path.mkdir:
2 X) Y: R% D3 S: w
    from pathlib import PathPath("/my/directory").mkdir(parents=True,exist_ok=True)( M, H6 F# B3 m' i7 I
旧版 Python,我看到两个质量好的答案,每个都有一个小缺陷,所以我会给出我的看法:% j/ V3 v4 x: ~7 q3 W  ?) C. Z
尝试os.path.exists,并os.makedirs考虑创作。
! w- a' m$ e! T) p' I: K' d' j% d
    import osif not os.path.exists(directory):    os.makedirs(directory)
    5 F% c  \/ H' ~
如评论等地方所述,有竞争条件 - 如果在os.path.exists和os.makedirs在调用之间创建目录,os.makedirs并显示失败OSError. 不幸的是,一揽子捕获OSError而且继续不是万无一失的,因为它会忽略其他因素导致的目录创建失败,如权限不足、磁盘满等。8 d' v7 g0 ^9 N% z- w
捕获是一种选择OSError并检查嵌入的错误代码:
9 S$ [, u# y) H* i+ i/ Y
    import os,errnotry:    os.makedirs(directory)except OSError as e:    if e.errno != errno.EEXIST:        raise
    3 q) M3 _) n( `* L0 [# B
或者,可能有第二个os.path.exists,但假设另一个人在第一次检查后创建了目录,然后在第二次检查前删除它——我们仍然可能被愚弄。- W+ U9 E7 J8 L7 w0 y6 L
根据不同的应用程序,并发操作的风险可能大于或小于其他因素(如文件权限)。在选择实现之前,开发人员必须更多地了解正在开发的特定应用程序及其预期环境。
6 n* }6 i/ s& i* m: g现代版Python 通过公开FileExistsError(在 3.3  中)…
- A% H/ Z. m# U
    try:    os.makedirs("path/to/directory")except FileExistsError:    # directory already exists    pass
    & p( k2 T0 \2 L" m$ W. Q8 c" i0 [
…并允许调用关键字参数os.makedirs``exist_ok(在 3.2  中)。8 W4 e4 p' o& B$ h, |" d/ V
    os.makedirs("path/to/directory",exist_ok=True)  # succeeds even if directory exists.
    6 a  M& @, g, T
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则