1、使用os
import os
os.path.exists(test_dir)
例如:D:/Python/test.py
Ture表示存在
False表示不存在
test_dir:需要是绝对路径,下面都是需要绝对路径
2、使用open
try:
f =open()
f.close()
except IOError:
print “File is not accessible.”
3、Pathlib
pathlib模块在Python3版本中是内建模块,但是在Python2中是需要单独安装三方模块。
import pathlib
path = pathlib.Path(“path/file”)
检查路径是否存在
path.exist()
检查路径是否是文件
path.is_file()
是否是路径
path.is_dir
Python判断文件是否存在
最新推荐文章于 2024-07-28 15:46:11 发布