7

说文件'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 但是同样,这是不正确的。该文件甚至在我的计算机上都不存在。有没有办法从我当前工作的任何目录中获取正确的绝对路径?(除了定义一个新功能)

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

4

5 回答 5

13

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

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

于 2012-04-05T09:19:59.503 回答
1

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

从文档:

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

于 2012-04-05T09:22:31.123 回答
0

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

于 2012-04-05T09:25:07.670 回答
0

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

os.path.join(root, f)

于 2020-02-03T20:49:51.513 回答
0

问题应该是以前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
于 2017-05-03T13:06:46.960 回答