zoukankan      html  css  js  c++  java
  • Python 判断文件/目录是否存在

    使用 os 模块

    • 判断文件是否存在

      os.path.isfile(path)
      
    • 判断目录是否存在

      os.path.isdir(path)
      
    • 判断路径是否存在

      # 使用 path 模块
      os.path.exists(path)
      
      # 使用 access() 方法
      os.access(path, os.F_OK)
      

    使用 open 函数和异常捕获

    如果直接用 open() 函数打开一个不存在的文件时,程序会抛出异常,我们可以通过 try 语句来捕获异常以达到判断文件是否存在的目的。

    如果文件不存在,open() 函数会抛出 FileNotFoundError 异常。如果文件无操作权限,则会抛出 PersmissionError 异常。

    filePath = '/path/to/file'
    
    try:
        file = open(filePath)
        file.close()
    except FileNotFoundError:
        print("No such file or directory: '%s'" % filePath)
    except IsADirectoryError:
        print("Is a directory: '%s'" % filePath)
    except PermissionError:
        print("Permission denied: '%s'" % filePath)
    else:
        print("File is exist: '%s'" % filePath)
    

    使用 pathlib 模块

    import pathlib
    
    path = pathlib.Path('path/to/file')
    
    # 判断路径是否存在
    path.exists()
    
    # 判断是否为文件
    path.is_file()
    
    # 判断是否为目录
    path.is_dir()
    

    个人博客同步地址:
    https://shockerli.net/post/python-determine-file-exist/

  • 相关阅读:
    0xx_nodeJS
    0xx_jQuery
    0xx_正则表达式
    0xx_ES6
    centos重启关机命令
    tomcat服务开机启动脚本
    mysql授权总结
    centos创建文件命令
    svn如果无法连接有可能导致右键卡
    简单导出excel
  • 原文地址:https://www.cnblogs.com/shockerli/p/python-determine-file-exist.html
Copyright © 2011-2022 走看看