python的isdir、lexists、exists、isfile有什么区别

测试代码

import os
from os import path
if __name__ == '__main__':


    truth_pth="run/data/images"
    no_pth="run1/data/images"
    broken_pth="run/images"
    file_pth="run/data/images/1.png"
    nofile_pth = "run/data/images/2.png"

    pths = [truth_pth,no_pth,broken_pth,file_pth,nofile_pth]

    for p in pths:
        print(f"isdir({p})",path.isdir(p))
    for p in pths:
        print(f"lexists({p})",path.lexists(p))
    for p in pths:
        print(f"exists({p})",path.exists(p))
    for p in pths:
        print(f"isfile({p})", path.isfile(p))


 此时的目录

python的isdir、lexists、exists、isfile有什么区别_第1张图片

测试结果

isdir(run/data/images) True
isdir(run1/data/images) False
isdir(run/images) False
isdir(run/data/images/1.png) False
isdir(run/data/images/2.png) False
lexists(run/data/images) True
lexists(run1/data/images) False
lexists(run/images) False
lexists(run/data/images/1.png) True
lexists(run/data/images/2.png) False
exists(run/data/images) True
exists(run1/data/images) False
exists(run/images) False
exists(run/data/images/1.png) True
exists(run/data/images/2.png) False
isfile(run/data/images) False
isfile(run1/data/images) False
isfile(run/images) False
isfile(run/data/images/1.png) True
isfile(run/data/images/2.png) False

结论

lexist和exist几乎一样,只要路径存在就可以,不在乎是文件还是目录。

isdir判断是不是已经存在的目录

isfile判断是不是已经存在的文件

你可能感兴趣的:(python,开发语言)