Search code examples
pythonpython-3.xfilepathpathlib

How to remove a file from Path object in Pathlib module?


I have a Path Object representing C:\Users\users\Downloads\img.jpg. How do I get it so the Path only represents C:\Users\user\Downloads? I don't want to delete the file, but rather go back in the Path object itself.

from pathlib import Path
path = Path('C:/Users/user/Downloads/img.jpg')
# Want to get path only to C:\Users\user\Downloads

Solution

  • I would utilize the PurePath class within pathlib as follows:

    from pathlib import PurePath
    path = PurePath('C:/Users/user/Downloads/img.jpg')
    parent = path.parents[0]
    

    This yields: PureWindowsPath('C:/Users/users/Downloads')