【问题标题】:Weird path behavior when using os.path and pathlib Mac OSX Catalina使用 os.path 和 pathlib Mac OSX Catalina 时的奇怪路径行为
【发布时间】:2020-04-20 06:02:47
【问题描述】:

我有一个名为 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')]

【问题讨论】:

    标签: python-3.x python-os pathlib


    【解决方案1】:

    使用函数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')
    

    【讨论】:

    • 好吧,我的错我应该把它转换成一个字符串,它可以工作。
    猜你喜欢
    • 2012-02-03
    • 1970-01-01
    • 2014-12-03
    • 1970-01-01
    • 2019-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-16
    相关资源
    最近更新 更多