Python os.path.abspath的误解

10 浏览
0 Comments

Python os.path.abspath的误解

我有以下代码:

directory = r'D:\images'
for file in os.listdir(directory):
    print(os.path.abspath(file))

我想要以下输出:

  • D:\\images\\img1.jpg
  • D:\\images\\img2.jpg以此类推

但我得到了不同的结果:

  • D:\\code\\img1.jpg
  • D:\\code\\img2.jpg

其中D:\\code是我的当前工作目录,结果与

os.path.normpath(os.path.join(os.getcwd(), file))

相同。所以,问题是:

os.path.abspath的目的是什么,为什么我必须使用

os.path.normpath(os.path.join(directory, file))

来获取我的文件的实际绝对路径?如果可能,请展示真实的用例。

admin 更改状态以发布 2023年5月23日
0
0 Comments

listdir 会返回一个文件夹里的文件名列表,但是不会包含文件夹的名字。没有其他信息的情况下,abspath 只能基于唯一知道的目录,也就是当前工作目录,来形成绝对路径。你可以在循环之前改变工作目录:

os.chdir(directory)
for f in os.listdir('.'):
    print(os.path.abspath(f))

0
0 Comments

问题出在您对os.listdir()的理解上,而不是os.path.abspath()os.listdir()返回目录中每个文件的名称。这将给您:

img1.jpg
img2.jpg
...

当您将这些传递给os.path.abspath()时,它们被视为相对路径。这意味着它是相对于您执行代码的目录。这就是为什么您会得到“D:\code\img1.jpg”的原因。

相反,您想要做的是将文件名与您列出的目录路径连接起来。

os.path.abspath(os.path.join(directory, file))

0