Python os 模块

Python os.path.exists() 函数用于判断路径是否存在

语法

os.path.exists(path)

参数

path:要判断的路径。

返回值

返回布尔值:路径存在为 True。区分文件/目录用 isfile/isdir。

示例

import os

print(os.path.exists("data.txt"))   # True/False
print(os.path.exists("no_such"))    # False

# 区分文件/目录
print(os.path.isfile("data.txt"))   # 是文件?
print(os.path.isdir("data"))        # 是目录?

# 读文件前判断
if os.path.exists("config.json"):
    with open("config.json") as f:
        print(f.read())

注意事项

读写文件、删除前先用 exists/isfile 判断,避免异常。os.path 还有 basename/dirname/splitext 等。