Search code examples
python-3.xpython-ospathlib

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


I have an image called image1.png its real path on my macbook is :

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

and the image is found by calling:

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

let's say I want to get the same path above by calling

os.path.abspath(images[0])

or

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

and the current working directory is:

/Users/emadboctor/Desktop/another

Expected path: /Users/emadboctor/Desktop/images/image1.png

What I actually get: /Users/emadboctor/Desktop/another/image1.png

To reproduce the problem here are the sequence of steps:

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

How to get the path I'm expecting without hardcoding the correct prefix?

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

Solution

  • Use the function 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')