E
E
etetetetetete2016-07-16 22:54:04
Python
etetetetetete, 2016-07-16 22:54:04

How to return the result of a recursive function to a variable?

Wrote a recursive function to search for nested directories in the root.
The problem is that you need to return the list to a variable, but not as I did, with the help of global, but with the help of return.

import os


def SearchDir(path):
    global z
    if os.path.exists(path):
        if os.listdir(path):
            for d in os.listdir(path):
                if os.path.isdir(os.path.join(path, d)):
                    z += [(os.path.join(path, d))]
                    SearchDir(os.path.join(path, d))
        else:
            return print('The directory is empty')
    else:
        return print('The directory does not exist')

path = r'C:\test'
z = []

SearchDir(path)
print(z)

PS. Python 3

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
sim3x, 2016-07-16
@sim3x

php style
use https://docs.python.org/3/library/os.html#os.walk
print no need to write in return

A
Alexey Cheremisin, 2016-07-16
@leahch

I hope it's understandable.

def SearchDir(path):
   z= []
   def _SearchDir(path):
      ...
      z.append("abc")
      _SearchDir(newpath)
      ...
   _SearchDir(path)
   return z

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question