python基础:Python判断文件是否存在的三种方法(os.path.exsist, os.path.isfile, try | 您所在的位置:网站首页 › 请检查该文件是否有正确的权限 › python基础:Python判断文件是否存在的三种方法(os.path.exsist, os.path.isfile, try |
博客原文:http://www.spiderpy.cn/blog/detail/28 目录
前言: 一、使用os模块 二、使用try-catch 前言:通常在读写文件之前,需要判断文件或目录是否存在,不然某些处理方法可能会使程序出错。所以最好在做任何操作之前,先判断文件是否存在。 这里将介绍三种判断文件或文件夹是否存在的方法,分别使用os模块、Try语句、pathlib模块。 一、使用os模块 os模块中的os.path.exists()方法用于检验文件是否存在 判断文件是否存在 import os os.path.exists(test_file.txt) #True os.path.exists(no_exist_file.txt) #False 判断文件夹是否存在 import os os.path.exists(test_dir) #True os.path.exists(no_exist_dir) #False所以 os.path.exists() 它可以判断文件、文件夹是否存在,当然也可以写相对路径。 其实这种方法还是有个问题,假设你想检查文件“test_data”是否存在,但是当前路径下有个叫“test_data”的文件夹,这样就可能出现误判。为了避免这样的情况,可以这样: 只检查文件是否存在 import os os.path.isfile("test-data")通过这个方法,如果文件”test-data”不存在将返回False,反之返回True。
插入一个使用场景:flask检测配置文件是否存在 flask使用 .env 作为环境变量的配置文件,然后使用 python-dotenv 模块将 .env 文件中配置的参数写入环境变量中。那么就需要检测 .env 文件是否存在,就是使用的 os.path.isfile(xxx)。所以我们在自己写模块的时候,也可以使用 isfile 来判断配置文件是否存在。flask源码如下所示: if dotenv is None: if path or os.path.isfile(".env") or os.path.isfile(".flaskenv"): click.secho( " * Tip: There are .env or .flaskenv files present." ' Do "pip install python-dotenv" to use them.', fg="yellow", err=True, ) return False上面文件表达的意思是:如果 .env 或者 .flaskenv 文件存在,但是python-dotenv模块却没有安装,那么就会提醒你去安装python-dotenv模块。
即使文件存在,你可能还需要判断文件是否可进行读写操作。 判断文件是否可做读写操作使用os.access()方法判断文件是否可进行读写操作。 语法: os.access(path, mode)path为文件路径,mode为操作模式,有这么几种: os.F_OK: 检查文件是否存在; os.R_OK: 检查文件是否可读; os.W_OK: 检查文件是否可以写入; os.X_OK: 检查文件是否可以执行 import os if os.access("/file/path/foo.txt", os.F_OK): print "Given file path is exist." if os.access("/file/path/foo.txt", os.R_OK): print "File is accessible to read" if os.access("/file/path/foo.txt", os.W_OK): print "File is accessible to write" if os.access("/file/path/foo.txt", os.X_OK): print "File is accessible to execute"该方法通过判断文件路径是否存在和各种访问模式的权限返回True或者False。 二、使用try-catch 可以在程序中直接使用open()方法来检查文件是否存在和可读写。 如果你open的文件不存在,程序会抛出错误,使用try语句来捕获这个错误。 程序无法访问文件,可能有很多原因: 如果你open的文件不存在,将抛出一个FileNotFoundError的异常; 文件存在,但是没有权限访问,会抛出一个PersmissionError的异常。 所以可以使用下面的代码来判断文件是否存在: try: f =open() f.close() except FileNotFoundError: print "File is not found." except PermissionError: print "You don't have permission to access this file."其实没有必要去这么细致的处理每个异常,上面的这两个异常都是IOError的子类。所以可以将程序简化一下: try: f =open() f.close() except IOError: print "File is not accessible."
|
CopyRight 2018-2019 实验室设备网 版权所有 |