• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

python判断文件是否存在

python 搞java代码 3年前 (2022-05-21) 28次浏览 已收录 0个评论

在操作文件前,检查文件是否存在也是一个良好的编程习惯。通常来说,有三种常见方式来判断文件夹或文件是否存在,分别是os模块,try语句和pathlib模块。

搞代码网,大量的免费python教程,欢迎在线学习!

os模块

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

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

www#gaodaima.com来源gao@dai!ma.com搞$代^码网搞代码

这种用法既能检测文件也能检测文件夹,这也带来问题,假如我想找一个命名为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"

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()

更多教程,请点击搞代码网

来源:搞代码网:原文地址:https://www.gaodaima.com


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:python判断文件是否存在

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址