I want to use a list comprehension that returns the filenames of all files in a list of dirs. I've written the following list comprehension which fails since d is not defined at the time of os.listdir(d) on the first iteration. How can I restructure this list comprehension such that it works?
[f for f in os.listdir(d) for d in dirs if os.path.isfile(os.path.join(d, f))]
NameError: global name 'd' is not defined
You need to order your
for
loops in the same order you'd nest them; you have them swapped. Move thefor d in dirs
part to the front:If it helps, write out the loops as regular
for
statements first:and just join the lines and remove the
:
colons to create the list comprehension order.