0

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

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.