python - 你好,为什么当我使用相对路径时文件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()}")
解决方案
您的第二个示例是解析相Desktop/hello.txt
对于当前工作目录的相对路径,因此它正在检查是否/Users/sergii/Documents/Desktop/hello.txt
存在。
推荐阅读
- python - 如何在 django 模板中传递产品下载链接
- javascript - 如何定义动态生成的按钮上的操作?
- c# - .Net Core Swashbuckle 在重定向时跳过授权标头
- html - 使用 JINJA 测试 AJAX 值内联 HTML
- regex - Groovy string replaceAll 无法正常工作
- google-apps-script - 如何从谷歌电子表格的另一张表中获取带有文本的彩色单元格?
- sql - 我如何使用我的数据库中的“不同”
- javascript - 如何用图案填充图像(衬衫上的织物)
- mongodb - 在 MongoDB 中查找包含特殊字符的字段的文档
- gitlab - 在 openshift 项目中看不到 gitlab-runner 模板