python中,判断文件是否存在的几种方法
python语句如何判断文件是否存在某个目录下,我介绍下面几种方法吧:
1.使用python自带的OS模块
2.使用if加else判断
3.使用try异常处理方法
4.使用pathlib模块
1.使用OS模块:
os.path.exists(path)
方法可直接用于检验文件夹/文件是否存在,如果路径 path 存在,返回 True;如果路径 path 不存在,返回 False。
判断文件是否存在:
import os
os.path.exists(test_file.txt)
#返回True或false
判断文件夹:
import os
os.path.exists(test_dir)
#返回True或false
即是文件存在,你可能还需要判断文件是否可进行读写操作
判断文件是否可做读写操作:
使用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"
2.使用if和else:
思路为获取目录下所有的文件及文件夹,存放在一个列表中,然后用if、else进行判断文件名是否存在列表:
import os
#查看screenshot目录下的文件
class dir_file:
"""创建一个获取目录下所有文件的名称"""
def file(self):
filedir = os.path.dirname(__file__)#返回文件路径
# print(filedir)
file = os.listdir(filedir) #方法用于返回指定的文件夹包含的文件或文件夹的名字的列表。不包括.和..文件
print("screenshot文件下包含:{}".format(file))
return file
def dirile(self):
filedir = os.path.dirname(__file__) # 返回文件路径
print(filedir)
return filedir
if __name__ == '__main__':
file = dir_file().file()
f = '文件名'
if f in file:
存在的时候做操作
elif f not in file:
不存在的时候做操作
3.使用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."
4.使用pathlib模块
pathlib模块在Python3版本中是内建模块,但是在Python2中是需要单独安装三方模块。
使用pathlib需要先使用文件路径来创建path对象。此路径可以是文件名或目录路径。
检查路径是否是文件:
from pathlib import Path
path = pathlib.Path("path/file")
path.is_file()#返回true或false
检查路径是否存在:
from pathlib import Path
path = pathlib.Path("path/file")
path.is_file()#返回true或false