来源:
Python那些事
ID:
PythonSomething
使用 os 模块
os.path.isfile(path)
os.path.isdir(path)
os.path.exists(path)
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()
Linux云计算及运维架构师高薪实战班“2019年03月04日即将开课中,