dragon2fly
dragon2fly

Reputation: 2429

Regular expression to match all path in the tree

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

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 ?

Upvotes: 0

Views: 770

Answers (2)

vks
vks

Reputation: 67988

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.

Upvotes: 1

Sheshananda Naidu
Sheshananda Naidu

Reputation: 1025

import os

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

It prints

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

Upvotes: 1

Related Questions