【问题标题】:Problems while getting absolute path?获取绝对路径时出现问题?
【发布时间】:2019-04-09 21:27:31
【问题描述】:

我想阅读以下文件,您可以看到它不完整:

file = 'dir2/file.hdf5'

但是,我想得到file(*)的完整路径:

'/home/user/git_hub_repo/dir1/dir2/file.hdf5'

但是,当我这样做时:

from pathlib import Path
filename = Path('dir2/file.hdf5').resolve()
print(filename)

我明白了:

'/home/user/git_hub_repo/dir2/file.hdf5'

这是错误的,因为在检索到的路径中缺少 dir1我怎样才能获得 (*) 路径

请注意,在我的终端中,我在:

/home/user/git_hub_repo/

【问题讨论】:

  • 抱歉,python 还不支持读心术。你怎么期望它知道你想要一个dir1
  • resolve() 只是将当前目录连接到您给它的路径。它不会神奇地知道你真的是指那里的那个文件,名称相似
  • 我知道...获取该路径的正确方法是什么?
  • filename.is_file() 的输出是什么? Path() 从您的当前目录开始,这可能是错误的。
  • filename = Path('dir1/dir2/file.hdf5').resolve()

标签: python python-3.x io path


【解决方案1】:

如果你的当前目录是

/home/user/git_hub_repo/

你的文件在

/home/user/git_hub_repo/dir1/dir2/file.hdf5

你应该改变这个

file = 'dir2/file.hdf5'

file = 'dir1/dir2/file.hdf5'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-14
    • 2011-07-06
    • 1970-01-01
    • 1970-01-01
    • 2012-09-03
    • 1970-01-01
    • 1970-01-01
    • 2022-06-10
    相关资源
    最近更新 更多