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.
JavaScript
x
4
1
from pathlib import Path
2
path = Path('C:/Users/user/Downloads/img.jpg')
3
# Want to get path only to C:UsersuserDownloads
4
Advertisement
Answer
I would utilize the PurePath class within pathlib as follows:
JavaScript
1
4
1
from pathlib import PurePath
2
path = PurePath('C:/Users/user/Downloads/img.jpg')
3
parent = path.parents[0]
4
This yields: PureWindowsPath('C:/Users/users/Downloads')