【问题标题】:Hello , why does it return False for file exists() when im using relative path but return True when path is absolute? thanks你好,为什么当我使用相对路径时文件exists()返回False,但当路径是绝对路径时返回True?谢谢
【发布时间】:2021-07-08 18:43:46
【问题描述】:
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()}")

【问题讨论】:

    标签: python path pathlib


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-01-16
      • 1970-01-01
      • 2010-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-16
      相关资源
      最近更新 更多