一般在读写文件以前,须要判断文件或目录是否存在,否则某些处理方法可能会使程序出错。因此最好在作任何操做以前,先判断文件是否存在。python
这里将介绍三种判断文件或文件夹是否存在的方法,分别使用os模块
、Try语句
、pathlib模块
。markdown
os模块中的os.path.exists()
方法用于检验文件是否存在。app
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()
方法,判断文件和文件夹是同样。ide
其实这种方法仍是有个问题,假设你想检查文件“test_data”是否存在,可是当前路径下有个叫“test_data”的文件夹,这样就可能出现误判。为了不这样的状况,能够这样:ui
import os os.path.isfile("test-data")
经过这个方法,若是文件”test-data”不存在将返回False,反之返回True。this
便是文件存在,你可能还须要判断文件是否可进行读写操做。url
使用os.access()
方法判断文件是否可进行读写操做。spa
语法:code
os.access(path, mode)对象
path为文件路径,mode为操做模式,有这么几种:
os.F_OK: 检查文件是否存在;
os.R_OK: 检查文件是否可读;
os.W_OK: 检查文件是否能够写入;
os.X_OK: 检查文件是否能够执行
该方法经过判断文件路径是否存在和各类访问模式的权限返回True或者False。
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"
能够在程序中直接使用open()
方法来检查文件是否存在和可读写。
语法:
open()
若是你open的文件不存在,程序会抛出错误,使用try语句来捕获这个错误。
程序没法访问文件,可能有不少缘由:
若是你open的文件不存在,将抛出一个FileNotFoundError
的异常;
文件存在,可是没有权限访问,会抛出一个PersmissionError
的异常。
因此可使用下面的代码来判断文件是否存在:
try:
f =open()
f.close()
except FileNotFoundError:
print "File is not found."
except PersmissionError:
print "You don't have permission to access this file."
其实没有必要去这么细致的处理每一个异常,上面的这两个异常都是IOError
的子类。因此能够将程序简化一下:
try:
f =open()
f.close()
except IOError:
print "File is not accessible."
使用try语句进行判断,处理全部异常很是简单和优雅的。并且相比其余不须要引入其余外部模块。
pathlib模块在Python3版本中是内建模块,可是在Python2中是须要单独安装三方模块。
使用pathlib须要先使用文件路径来建立path对象。此路径能够是文件名或目录路径。
path = pathlib.Path("path/file")
path.exist()
path = pathlib.Path("path/file")
path.is_file()
博客原文:http://www.spiderpy.cn/blog/detail/28