3

I'm writing a program that needs to explore all possible subdirectories of a given path topdown. My problem is that I need to do things before calling recursion and after finish recursion and os.walk() doesn't allow this. More precisely the recursion in the directories subtree that I need is:

(Note: is not real Python code, just Python-like code to explain what I need to do)

def recursion(path):
    action1()
   for subdir in path:
       recursion(path+subdir)
   action2()

while what I can do with os.walk() is simply:

def recursion(path):
    action1()
    action2()
    for subdir in path:
        recursion(path+subdir)

Is there any solution?

L.A.
  • 243
  • 2
  • 12

2 Answers2

1

You can use os.scandir instead:

def recursion(path):
    action1()
    for entry in os.scandir(path):
        if entry.is_dir():
            recursion(os.path.join(path, entry.name))
    action2()

or if you're using Python 3.4 or earlier versions, use the slower os.listdir instead:

def recursion(path):
    action1()
    for name in os.listdir(path):
        full_path = os.path.join(path, name)
        if os.path.isdir(full_path):
            recursion(full_path)
    action2()
blhsing
  • 91,368
  • 6
  • 71
  • 106
1

Or you could use glob and split()

import glob
path='this/is/your/path'
pathElementList=path.split('/')
for x in range(len(pathElementList)):
    directoryToDoActionIn='/'.join(pathElementList[0:x])
    filesindir=glob.glob(directoryToDoActionIn+'/')
    #do action with files here
zabop
  • 6,750
  • 3
  • 39
  • 84