0

I have a folder tree like /country/province/city/home that I want to get all sub-paths in it:

  • /country
  • /country/province
  • /country/province/city
  • /country/province/city/home

I can use pattern (?<=/)[\w]* to get all the words and then join them one by one with '/'.join(). But is there any way to achieve all the sub-paths with one regex ?

dragon2fly
  • 2,309
  • 19
  • 23
  • http://stackoverflow.com/questions/14798220/how-can-i-search-sub-folders-using-glob-glob-module-in-python might answer your question. – brimil01 Jan 08 '15 at 06:29
  • Use [os.path.split](https://docs.python.org/2/library/os.path.html#os.path.split) – nhahtdh Jan 08 '15 at 06:34
  • 1
    can't be done with basic regex (a certain part of the string can only be part of one match) but lookahead might work http://stackoverflow.com/a/18751542/412529 – jnnnnn Jan 08 '15 at 06:41
  • While it is possible to get overlapping matches by placing a capturing group inside a lookahead, each match must still start from a different position. – Janne Karila Jan 08 '15 at 13:05

2 Answers2

1
import os

for root, dirs, files in os.walk("."):
      print root

It prints

/country
/country/province
/country/province/city
/country/province/city/home
Sheshananda Naidu
  • 905
  • 1
  • 9
  • 10
  • This approach only works when the path is exist. But what I have is a string of path that I'm going to create. That's why I need regex – dragon2fly Jan 08 '15 at 06:54
1
x="/country/province/city/home"
y= re.split(r"(?<=[^/])\/",x)
str=y[0]
print str
for x in y[1:]:
    str=str+"/"+x
    print str

Try this.

vks
  • 67,027
  • 10
  • 91
  • 124
  • @dragon2fly see here https://regex101.com/r/sH8aR8/20 Once you split by this you have a list which we just loop thrugh and club together. – vks Jan 08 '15 at 06:52
  • so there is no direct way to get all subpaths at once? your `for loop` is another way of `'/'.join(x[:index])` of me – dragon2fly Jan 08 '15 at 07:00
  • @dragon2fly yes you are right.I dont know if it can be done via some module. – vks Jan 08 '15 at 07:01