对python os.path.abspath的误解 [英] Misunderstanding of python os.path.abspath

查看:272
本文介绍了对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等

但是我得到了不同的结果:

But I get different result:

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

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

where D:\code is my current working directory and this result is the same as

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

所以,问题是:我必须使用os.path.abspath的目的是什么

So, the question is: What is the purpose of os.path.abspath while I must use

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

获取我文件的REAL绝对路径?尽可能显示真实的用例.

to get REAL absolute path of my file? Show real use-cases if possible.

推荐答案

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

The problem is with your understanding of os.listdir() not os.path.abspath(). os.listdir() returns the names of each of the files in the directory. This will give you:

img1.jpg
img2.jpg
...

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

When you pass these to os.path.abspath(), they are seen as relative paths. This means it is relative to the directory from where you are executing your code. This is why you get "D:\code\img1.jpg".

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

Instead, what you want to do is join the file names with the directory path you are listing.

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

这篇关于对python os.path.abspath的误解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆