温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

python检查文件是否存在的方法

发布时间:2020-08-03 11:59:24 来源:亿速云 阅读:164 作者:清晨 栏目:编程语言

这篇文章主要介绍python检查文件是否存在的方法,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

os模块中的os.path.exists(path)可以检测文件或文件夹是否存在,path为文件/文件夹的名字/绝对路径。返回结果为True/False

print os.path.exists("/untitled/chapter3.py")print os.path.exists("chapter3.py")

这种用法既能检测文件也能检测文件夹,这也带来问题,假如我想找一个命名为helloworld的文件,使用exists可能命中同名的helloworld文件夹。这时使用os.path.isdir()和os.path.isfile()可以加以区分。如果进一步想判断是否可以操作文件,可以使用os.access(path, model),model为操作模式,具体如下

if __name__ == '__main__':
    if os.access("/untitled/chapter3.py", os.F_OK):
        print "File path is exist."

    if os.access("/untitled/chapter3.py", os.R_OK):
        print "File is accessible to read"

    if os.access("/untitled/chapter3.py", os.W_OK):
        print "File is accessible to write"

    if os.access("/untitled/chapter3.py", os.X_OK):
        print "File is accessible to execute"

python学习网,免费的python学习网站,欢迎在线学习!

try语句

对文件最简单的操作方法是直接使用open()方法,但是文件不存在,或发生权限问题时open方法会报错,所以配合try语句使用来捕捉一异常。try...open语法简单优雅,可读性强,而且不需要引入任何模块

if __name__ == '__main__':    
    try:
     f = open("/untitled/chapter3.py")
     f.close()    
   except IOError:        
       print "File is not accessible."

pathlib模块

在python2中pathlib属于第三方模块,需要单独安装。但是python3中pathlib已经是内建模块了

pathlib用法简单,与open类似。首先使用pathlib创建对象,进而使用exists(),is_file()等方法

if __name__ == '__main__':
    path = pathlib.Path("chapter3.py")
    print path.exists()
    print path.is_file()

以上是python检查文件是否存在的方法的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI