使用 os.path 和 pathlib Mac OSX Catalina 时奇怪的路径行为

Weird path behavior when using os.path and pathlib Mac OSX Catalina

我有一个名为 image1.png 的图像,它在我的 macbook 上的真实路径是:

/Users/emadboctor/Desktop/images/image1.png

图像是通过调用找到的:

images = os.listdir('/Users/emadboctor/Desktop/images/image1.png')

假设我想通过调用

获得与上面相同的路径

os.path.abspath(images[0])

pathlib.Path(images[0]).absolute()

当前工作目录是:

/Users/emadboctor/Desktop/another

预期路径:/Users/emadboctor/Desktop/images/image1.png

我实际得到的是:/Users/emadboctor/Desktop/another/image1.png

要重现此问题,请按以下步骤操作:

>>> import os
>>> os.getcwd()
'/Users/emadboctor/Desktop/another'
>>> os.path.abspath('../images/image1.png')
'/Users/emadboctor/Desktop/images/image1.png'  # This is the correct/expected path
>>> os.listdir('../images')
['image1.png']
>>> images = [os.path.abspath(image) for image in os.listdir('../images')]
>>> images
['/Users/emadboctor/Desktop/another/image1.png']  # This is the unexpected/incorrect path
>>> import pathlib
>>> pathlib.Path('../images/image1.png').parent.absolute()
PosixPath('/Users/emadboctor/Desktop/another/../images')  # This is also the unexpected/incorrect path

如何在不对正确前缀进行硬编码的情况下获得我期望的路径?

[f'/Users/emadboctor/Desktop/images/{image}' for image os.listdir('../images')]

使用函数resolve.

>>> from pathlib import Path
>>>
>>> Path.cwd()
WindowsPath('d:/Docs/Notes/Notes')
>>> p = Path('../../test/lab.svg')
>>> p
WindowsPath('../../test/lab.svg')
>>> p.absolute()
WindowsPath('d:/Docs/Notes/Notes/../../test/lab.svg')
>>> p.absolute().resolve()
WindowsPath('D:/Docs/test/lab.svg')