Misunderstanding of python os.path.abspath

后端 未结 3 1950
梦如初夏
梦如初夏 2020-12-24 12:40

I have following code:

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

and I want next outp

3条回答
  •  滥情空心
    2020-12-24 13:25

    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
    ...
    

    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))
    

提交回复
热议问题