Answer the question
In order to leave comments, you need to log in
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)
Answer the question
In order to leave comments, you need to log in
php style
use https://docs.python.org/3/library/os.html#os.walk
print no need to write in return
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 questionAsk a Question
731 491 924 answers to any question