0

There are a lot of questions like this, and I've actually found a way to do it

for root, dirs, files in os.walk(".", topdown=False):
    for name in files:
        (os.path.join(root, name))

But how to put all those in a single list? I want that function to return a single list with all the paths, how can I do that?

Mereketh
  • 45
  • 1
  • 8
  • possible duplicate of [Getting a list of all subdirectories in the current directory](http://stackoverflow.com/questions/973473/getting-a-list-of-all-subdirectories-in-the-current-directory) – abhi Apr 23 '14 at 16:08
  • you can simply join your 2 loops – njzk2 Apr 23 '14 at 16:12

3 Answers3

1

As a list comprehension, it is as easy as:

filelist = [os.path.join(root, name) for root, dirs, files in os.walk(".", topdown=False) for name in files]

For lazy evaluation, you can turn it into a generator:

import os

filelist_gen = (os.path.join(root, name) for root, dirs, files in os.walk(".", topdown=False) for name in files)

for i, f in enumerate(filelist_gen):
    if i >= 3:
        break
    print(f)

You should use this approach if you will likely not loop over the entire filelist. A list comprehension would create a list of all files before accessing even the first item.

CodeManX
  • 11,159
  • 5
  • 49
  • 70
1

Just declare an empty list:

items = []

and then append to it at the end:

for name in files:
    items.append(os.path.join(root, name))
anon582847382
  • 19,907
  • 5
  • 54
  • 57
0

In general, if you have something like:

for x in y:
    some more stuff:
        foo # I have an item here!!

there are two approaches.

The naïve approach is to stick it all in a list immediately:

def all_in_a_list():
    things = []

    for x in y:
        some more stuff:
            things.append(foo) # I have an item here!!

    return things

A more Pythonic approach is to make a generator

def all_things():
    for x in y:
        some more stuff:
            yield foo # I have an item here!!

and turn it to a list if need be at the call-site:

list(all_things())
Veedrac
  • 58,273
  • 15
  • 112
  • 169