Nested list comprehension using os.walk

Trying to list all files in a specific directory (for example, "find" on Linux or "dir / s / b" on Windows).

I came up with the following nested list comprehension:

from os import walk from os.path import join root = r'c:\windows' #choose any folder here allfiles = [join(root,f) for f in files for root,dirs,files in walk(root)] 

Unfortunately, for the last expression, I get:

NameError: name 'files' is not defined

In connection with this issue, which (although it works), I cannot understand the syntax for understanding the nested list.

+4
source share
2 answers

You need to cancel the nesting;

 allfiles = [join(root,f) for root,dirs,files in walk(root) for f in files] 

See documentation :

When a list view is provided, it consists of one expression, followed by at least one for clause and zero or more for or if clauses. In this case, the elements of the new list are those that will be created by examining each of the for or if sentences of the block, nesting from left to right, and evaluating the expression to create the list element every time the innermost block is reached.

In other words, since you basically want the moral equivalent:

 allfiles = [] for root, dirs, files in walk(root): for f in files: allfiles.append(f) 

Your understanding of the list must match the same order.

+14
source

this is:

 allfiles = [join(root, f) for _, dirs, files in walk(root) for f in files] 
+5
source

Source: https://habr.com/ru/post/1441841/


All Articles