3

I want a dictionary of files:

files = [files for (subdir, dirs, files) in os.walk(rootdir)]

But I get,

files = [['filename1', 'filename2']] 

when I want

files = ['filename1', 'filename2']

How do I prevent looping through that tuple? Thanks!

Qantas 94 Heavy
  • 15,750
  • 31
  • 68
  • 83
atp
  • 30,132
  • 47
  • 125
  • 187
  • 3
    possible duplicate of [Flattening a shallow list in python](http://stackoverflow.com/questions/406121/flattening-a-shallow-list-in-python) – kennytm Jul 24 '10 at 19:20
  • Also [Making a flat list out of list of lists in python](http://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python) – John Kugelman Jul 24 '10 at 19:27
  • forget my files = [f for f in files for (subdir, dirs, files) in os.walk(rootdir)] I think that there are many side effects. I will delete the answer – luc Jul 24 '10 at 19:30

4 Answers4

7

Both of these work:

[f for (subdir, dirs, files) in os.walk(rootdir) for f in files]

sum([files for (subdir, dirs, files) in os.walk(rootdir)], [])

Sample output:

$ find /tmp/test
/tmp/test
/tmp/test/subdir1
/tmp/test/subdir1/file1
/tmp/test/subdir2
/tmp/test/subdir2/file2
$ python
>>> import os
>>> rootdir = "/tmp/test"
>>> [f for (subdir, dirs, files) in os.walk(rootdir) for f in files]
['file1', 'file2']
>>> sum([files for (subdir, dirs, files) in os.walk(rootdir)], [])
['file1', 'file2']
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
2
for (subdir, dirs, f) in os.walk(rootdir): files.extend(f)
Anycorn
  • 50,217
  • 42
  • 167
  • 261
2
files = [filename for (subdir, dirs, files) in os.walk(rootdir) for filename in files]
Tony Veijalainen
  • 5,447
  • 23
  • 31
0
import os, glob

files = [file for file in glob.glob('*') if os.path.isfile(file)]

if your files have extensions, then even simpler:

import glob
files = glob.glob('*.*')
marbdq
  • 1,235
  • 8
  • 5