I have a long file path and I need to extract last 3 subfolders. For example, if my path is:
a\b\c\d\e\f\g
then I need only last 3 folders:
e\f\g
How can I achieve that?
I have a long file path and I need to extract last 3 subfolders. For example, if my path is:
a\b\c\d\e\f\g
then I need only last 3 folders:
e\f\g
How can I achieve that?
You can use pathlib.PurePath.parts
like this:
import pathlib
p = pathlib.PureWindowsPath(r'a\b\c\d\e\f\g')
parts = p.parts[-3:]
# > ('e', 'f', 'g')
p3 = pathlib.PureWindowsPath(*parts)
print(p3) # -> e\f\g
(I'm using Linux so I specified PureWindowsPath
.)
The best practice to deal with paths is to use os
and it's seperator os.sep
to split the path into pieces. Use os.sep
instead of '\' or '/', as this makes it system independent.
import os
path = r'a\b\c\d\e\f\g'
path = os.path.normpath(path)
path_list = path.split(os.sep)
print(os.sep.join(path_list[-3:]))
It prints:
e\f\g
You can split the terms in \
and join it:
'\\'.join(path_name.split("\\")[-3:]