python判断文件是否存在

By 刘志军 , 2020-06-07, 分类: qa

python

判断文件或目录是否存在

import os
if os.path.exists("/path/to/file")
    #  存在
    pass
else:
    # 不存在
    pass

判断目录是否存在

import os
if os.path.isdir("/path"):
    #  存在
    pass
else:
    # 不存在
    pass

判断文件是否存在

import os
if os.path.isfile("/path"):
    #  存在
    pass
else:
    # 不存在
    pass

如果使用 python3, 还可以使用 pathlib 模块

>>> from pathlib import Path
>>> f = Path("./pip")
>>> f.exists()  # 文件或目录是否存在
True
>>> f.is_file()  # 文件是否存在
False
>>> f.is_dir()  # 目录是否存在
True

关注公众号「Python之禅」,回复「1024」免费获取Python资源

python之禅

猜你喜欢

2015-06-17
如何在Python中正确使用static、class、abstract方法
2020-06-13
python 中 xml 转换为 json
2017-12-26
5个酷毙的Python工具
2020-06-01
最新抖音去水印解析
2017-05-15
一步一步教你认识Python闭包
2022-03-13
从一段小代码开始学习如何重构
2013-10-30
Python“不为人知的”特性
2020-06-04
如何用Python执行linux命令
2020-06-07
python合并两个字典
2019-03-09
30个Python 小例子,帮你快速上手Python