如何解决你好,为什么当我使用相对路径时它为文件存在返回 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()}")
解决方法
您的第二个示例是解析相对于当前工作目录的相对路径 Desktop/hello.txt
,因此它正在检查 /Users/sergii/Documents/Desktop/hello.txt
是否存在。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。