Python中判断文件是否存在的三种方法
在进行文件读写操作的时候,需要先判断文件是否存在,以免引起程序异常。本文将介绍三种Python中判断文件是否存在的方法,分别使用了os控制模块、Try语句、pathlib模块。

1. 使用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()方法判断文件和文件夹是一样的。但是这种方法有一个问题,当你要判断的文件名与当前路径下的文件夹名相同时,会出现误判。此时可以使用os.path.isfile()方法只检查文件是否存在:
import os
os.path.isfile('test_data') # True
要判断文件是否可读写,可以使用os.access()方法来判断:
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. 使用Try语句
可以使用open()方法来检查文件是否存在和可读写,在程序中使用try语句捕获异常即可:
try:
f = open('filename', 'r')
f.close()
except IOError:
print('File not found or inaccessible')
以上代码中,如果open的文件不存在,程序会抛出FileNotFoundError异常;如果文件存在但没有权限访问,则抛出PermissionError异常。可以用上面两种异常的父类IOError来简化代码:
try:
f = open('filename', 'r')
f.close()
except IOError:
print('File not found or inaccessible')
3. 使用pathlib模块
Python3中自带pathlib模块,而Python2需要手动安装第三方模块。使用前需要先使用文件夹名称或文件目录路径创建path对象:
判断路径是否存在:
import pathlib
path = pathlib.Path('path/file')
path.exist()
判断路径是否是文件:
import pathlib
path = pathlib.Path('path/file')
path.is_file()
综上所述,本文详细介绍了Python中判断文件是否存在的三种方法,分别使用了os控制模块、Try语句、pathlib模块,可以根据具体需要选择合适的方法来使用。
原创文章,作者:小编小本本,如若转载,请注明出处:https://www.benjiyun.com/yunzhujiyunwei/vps-yunwei/6902.html
