1、Python 操作文件时,我们一般要先判断指定的文件或目录是否存在,不然容易产生异常 。
2、例如我们可以使用 os 模块的 os.path.exists() 方法来检测文件是否存在:
import os.path
os.path.isfile(fname)
3、如果你要确定他是文件还是目录,从 Python 3.4 开始可以使用 pathlib 模块提供的面向对象的方法 (Python 2.7 为 pathlib2 模块):
from pathlib import Path
my_file = Path(/path/to/file)
if my_file.is_file():
# 指定的文件存在
检测是否为一个目录:
if my_file.is_dir():
# 指定的目录存在
4、如果要检测路径是一个文件或目录可以使用 exists() 方法:
if my_file.exists():
# 指定的文件或目录存在
在 try 语句块中你可以使用 resolve() 方法来判断:
try:
my_abs_path = my_file.resolve()
except FileNotFoundError:
# 不存在
else:
【python python代码大全】 # 存在
- 孕妇饮食大全食谱大全 孕妇饮食大全
- 怪物猎人世界斩斧图鉴大全 怪物猎人世界斩斧图鉴
- 方与圆的名言警句 方与圆的名言警句大全
- 最简单的早餐做法大全 简单做的早餐食谱大全
- 柠檬葡萄方糕图片大全 柠檬葡萄方糕
- 驻马店车船税去哪里交 陇南车船税缴纳地址大全
- steam错误代码-101解决win10 steam错误代码-101解决win7
- 柑橘锈壁虱防治时间!锈壁虱用什么药管用及用药大全 锈壁虱危害的乌柑能吃吗
- 十一开头的成语大全 十一开头的成语
- 葡萄燕麦饼干 葡萄干燕麦牛奶饼干做法大全