首页 > 解决方案 > 你好,为什么当我使用相对路径时文件exists()返回False,但当路径是绝对路径时返回True?谢谢

问题描述

import pathlib

home1 =pathlib.Path("/Users/sergii/Desktop/hello.txt")
print(f"home 1 is located {home1.cwd()}")  #home 1 is located /Users/sergii/Documents
print(f"home 1 exists {home1.exists()}")   #home 1 exists True
print(f"home 1 is a file {home1.is_file()}\n")


home2 = pathlib.Path("Desktop/hello.txt")
print(f"home 2 is located {home2.cwd()}")  #home 2 is located /Users/sergii/Documents
print(f"home 2 exists {home2.exists()}")   #home 2 exists False
print(f"home 2 is a file {home2.is_file()}")

标签: pythonpathpathlib

解决方案


您的第二个示例是解析相Desktop/hello.txt对于当前工作目录的相对路径,因此它正在检查是否/Users/sergii/Documents/Desktop/hello.txt存在。


推荐阅读