Simple list comprehension

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 can I prevent a loop through this tuple? Thank!

+3
source share
4 answers

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)], [])

Output Example:

$ 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']
+7
source
files = [filename for (subdir, dirs, files) in os.walk(rootdir) for filename in files]
+3
source
for (subdir, dirs, f) in os.walk(rootdir): files.extend(f)
+2
source
import os, glob

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

if your files have extensions, then even easier:

import glob
files = glob.glob('*.*')
0
source

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


All Articles