an01 an01 - 3 months ago 11
Python Question

Return list built from a loop with lambda

I have a function to return a list of files and folders in a given folder (with recurse and only get files options), or just the file in a list if given path is not a folder:

def path_to_list(path, onlyFiles = False, recurse = False):
if os.path.isdir(path):
if onlyFiles:
if recurse:
result = []
for dirs in list(os.walk(path)):
result.append(dirs[2])
return result
else:
return next(os.walk(path))[2]
else:
return list(os.walk(path)) if recurse else next(os.walk(path))

return [path]


Trying to shorten this part:

result = []
for dirs in list(os.walk(path)):
result.append(dirs[2])
return result


I tried to use lambda with multiple syntaxes but haven't got any success. How do I directly return the result from the for loop? Thanks.

Answer

You can return list of directories by:

return [dir for _, _, dir in list(os.walk(path))]
Comments