Reputation: 417
I want to extract the parent folder from a raw path string. For string without r
prefix, I successfully extracted the file path.
from pathlib import Path
des_dirs = '/path/to/my/file'
Path(des_dirs).parents[0]
Output:
> PosixPath('/path/to/my')
For a raw string, I'm unable to extract the parent folder. What am I missing here? Thanks!
from pathlib import Path
des_dirs = r'C:\Users\pp\Desktop\IMAGE_DATA\resized\masks'
Path(des_dirs).parents[0]
Output:
> PosixPath('.')
A reproducible example here
Upvotes: 0
Views: 216
Reputation: 1919
By reading the documentation, You could have known how to do that, the documentation says that explicitly. It is literally the first section in the page. https://docs.python.org/3/library/pathlib.html
use pathlib.PureWindowsPath
.
from pathlib import PureWindowsPath
des_dirs = r'C:\Users\pp\Desktop\IMAGE_DATA\resized\masks'
print(PureWindowsPath(des_dirs).parents[0])
Result:
C:\Users\pp\Desktop\IMAGE_DATA\resized
Upvotes: 1