2

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?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
shweta
  • 45
  • 4
  • 1
    Step 1: https://stackoverflow.com/questions/3167154/how-to-split-a-dos-path-into-its-components-in-python; Step 2: https://stackoverflow.com/questions/646644/how-to-get-last-items-of-a-list-in-python – mkrieger1 Jul 24 '21 at 16:38
  • ```'\\'.join(path_name.split("\\")[-3:])```? –  Jul 24 '21 at 16:38

4 Answers4

2

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

wjandrea
  • 28,235
  • 9
  • 60
  • 81
2

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
devReddit
  • 2,696
  • 1
  • 5
  • 20
1

You can use rsplit() with maxsplit of 3 :

a = r'a\b\c\d\e\f\g'
print('\\'.join(a.rsplit('\\', 3)[1:]))

output:

e\f\g
S.B
  • 13,077
  • 10
  • 22
  • 49
0

You can split the terms in \ and join it:

'\\'.join(path_name.split("\\")[-3:]