In Python, I want to list all files in a set of directories. The best I’d like to get is a list. But at most I managed to make a nested list:
pics = os.path.expanduser('~/Pictures')
all_pics = [(d, os.listdir(d)) for d in os.listdir(pics)]
result:
[('folder1', ['file1', 'file2', ...]), ('folder2', ['file1', ...]), ...]
what I want:
[('folder1' 'file1'), ('folder1', 'file2'), ..., ('folder2', 'file1'), ...]
What I would like to get is a simple plain list, doesn’t matter of what (can be of tuples), just so that it hasn’t nested things, and I need no nested cycles in the code that parses it.
How can I do this with list comprehensions? Doing this gives me a product of 2 sets (dir names and filenames) which is wrong:
[(d, f) for f in os.listdir(os.path.join(pics, d)) for d in os.listdir(pics)]
You got the order of the for-loops wrong. It should be
Outermost loop first, innermost loop last.
I wonder why you didn’t get a
NameErrorford.