【问题标题】:os.path.abspath('file1.txt') doesn't return the correct pathos.path.abspath('file1.txt') 没有返回正确的路径
【发布时间】:2012-04-05 09:16:00
【问题描述】:

假设文件'file1.txt'的路径是/home/bentley4/Desktop/sc/file1.txt 假设我当前的工作目录是/home/bentley4

import os
os.path.abspath('file1.txt')

返回/home/bentley4/file1.txt

os.path.exists('file1.txt')

返回False。 如果我这样做了

os.path.abspath('file_that_does_not_exist.txt')

它返回/home/bentley4/file_that_does_not_exist.txt 但同样,这是不正确的。该文件甚至不存在于我的计算机上。有没有办法从我当前工作的任何目录中获取正确的绝对路径? (除了定义一个新函数)

所以这仅在我与现有文件位于同一目录中或在距该文件目录路径一个或更远的目录中时才有效?

【问题讨论】:

  • 这很好奇,os.path.abspath 应该可以工作。 os.getcwd() 返回什么? ...哦,d'oh,等等,您是说您在/home/bentley4 中并且您期望os.path.abspath 以某种方式在其子目录中找到一个文件?它不会那样做。
  • 你想做什么?您是否尝试在当前工作目录的任何子目录中按名称查找文件?

标签: python path


【解决方案1】:

os.path.abspath(filename) 返回从当前工作目录看到的绝对路径。它不检查文件是否真的存在。

如果您想要/home/bentley4/Desktop/sc/file1.txt 的绝对路径并且您在/home/bentley4 中,则必须使用os.path.abspath("Desktop/sc/file1.txt")

【讨论】:

  • 好吧,首先检查os.path.isabs()。但在这种情况下,是的。
【解决方案2】:

abspath 只是建立一个路径,它不检查任何关于现有文件的内容。

来自文档:

在大多数平台上,这等价于 normpath(join(os.getcwd(), path))。

【讨论】:

    【解决方案3】:

    你会得到os.path.abspath(__file__)的路径。

    【讨论】:

    • 这不起作用。 os.path.abspath('file1.txt') 的行为与 os.path.abspath('file1.txt') 相同。
    • @Bentley4 os.path.abspath('file1.txt') 只要 Python 存在,其行为就会始终与 os.path.abspath('file1.txt') 相同......跨度>
    【解决方案4】:

    问题应该是以前 cwd 使用 os.chdir(another_path) 并且它仍然在当前执行的上下文中加载。 所以修复应该是在另一个路径中的任务使用完成后恢复原始路径。
    示例:

      original_path = os.getcwd()
      os.chdir(another_path) 
      # here perform some operation over another_path
      os.chdir(original_path ) # here is the restore of the original path
    

    【讨论】:

      【解决方案5】:

      我正在处理同样的问题,我发现了这个,希望它可以帮助你:

      os.path.join(root, f)

      【讨论】:

        猜你喜欢
        • 2021-06-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-03-29
        相关资源
        最近更新 更多