四种方法:python
# 第一种 os.path.exists(file_path)ide
# 第二种 os.path.isfile(file_path)插件
# 第四种 os.access(file_path,mode)code
# 第五种 try+open() 或者with open()get
示例:it
import os import sys #判断文件是否存在 print(os.getcwd()) # vscode中 python插件不能自动cd到当前目录 file = os.path.join(sys.path[0],"test.txt") # 第一种 os.path.exists(file_path) print("os.path.exists method test") print(os.path.exists(file)) print(os.path.exists("test1.txt")) # 第二种 os.isfile(file_path) #这种方法判断文件夹也是同样的 print("os.path.isfile test") print(os.path.isfile(file)) print(os.path.isfile("test1.txt")) # 第三种 pathlib # python3.4后 内建pathlib模块 pythonp2版本须要安装 from pathlib import Path print("pathlib test") path = Path(file) print(path.is_file()) print(path.exists()) # 第四种 os.access(file_path,mode) """ os.F_OK: 检查文件是否存在 0; os.R_OK: 检查文件是否可读 1; os.W_OK: 检查文件是否能够写入 2; os.X_OK: 检查文件是否能够执行 3 """ print("os.access test") print(os.access(file,0)) print(os.access("test.py",0)) # 第五种 # try + open() # with open()
运行结果:class