Skip to content
Advertisement

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

I have a Path Object representing C:UsersusersDownloadsimg.jpg. How do I get it so the Path only represents C:UsersuserDownloads? 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:UsersuserDownloads

Advertisement

Answer

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

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement