OS
import os
if os.path.exists('filename.txt'):
# 文件或目录存在时,做什么事
else:
# 不存在时做什么事
if os.path.isfile('filename.txt'):
# 是文件做什么事
if os.path.isdir('filename'):
# 是目录做什么事
pathlib
from pathlib import Path
the_file = Path('filename.txt')
if the_file.is_file():
# 是文件做什么事
if the_file.is_dir():
# 是目录做什么事
if the_file.exists():
# 文件或目录存在时,做什么事