os.path.abspath('file1.txt') 不返回正确的路径



假设文件"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')

返回CCD_ 4。如果我做

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

返回/home/bentley4/file_that_does_not_exist.txt但同样,这是不正确的。我的电脑上根本不存在这个文件。有没有办法从我目前工作的任何目录中获得正确的绝对路径?(除了定义新功能外)

因此,只有当我与现有文件在同一目录中,或者在距离该文件目录路径一个或多个目录的目录中时,这才有效?

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

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

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

来自文档:

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

您将获得带有os.path.abspath(__file__)的路径。

问题应该是之前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

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

os.path.join(root,f)

最新更新