Reference Python 标准库 reference

Python pathlib.exists 参考

Python pathlib.exists 参考,整理标准库调用语法、参数、示例、返回值和常见错误。

语法

python
from pathlib import Path

exists = Path("docs/index.md").exists()

参数

  • path:文件或目录路径,可使用字符串或 Path 对象。
  • encoding:读取和写入文本时建议显式指定,例如 utf-8。

返回值

返回 Path 对象、文本内容、布尔值或 None;删除、重命名等操作会修改文件系统。

示例

python
from pathlib import Path

exists = Path("docs/index.md").exists()
print(exists)

常见错误

  • 相对路径会受当前工作目录影响,脚本中建议先确认基准目录。
  • 文本读写没有指定 encoding,跨系统运行时容易乱码。

相关内容