我想要的文件的字典:簡單的列表理解
files = [files for (subdir, dirs, files) in os.walk(rootdir)]
,但我得到,
files = [['filename1', 'filename2']]
時,我想
files = ['filename1', 'filename2']
如何避免通過元組循環?謝謝!
我想要的文件的字典:簡單的列表理解
files = [files for (subdir, dirs, files) in os.walk(rootdir)]
,但我得到,
files = [['filename1', 'filename2']]
時,我想
files = ['filename1', 'filename2']
如何避免通過元組循環?謝謝!
這兩項工作:
[f for (subdir, dirs, files) in os.walk(rootdir) for f in files]
sum([files for (subdir, dirs, files) in os.walk(rootdir)], [])
輸出示例:
$ 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']
for (subdir, dirs, f) in os.walk(rootdir): files.extend(f)
並在此之前'files = []'。 – 2010-07-24 20:23:47
files = [filename for (subdir, dirs, files) in os.walk(rootdir) for filename in files]
import os, glob
files = [file for file in glob.glob('*') if os.path.isfile(file)]
如果你的文件有擴展,那麼就更簡單了:
import glob
files = glob.glob('*.*')
[在python中展開淺層列表]的可能的副本(http://stackoverflow.com/questions/406121/flattening-a-shallow-list-in-python) – kennytm 2010-07-24 19:20:48
另請參見:[使平面列表脫離列表在Python中列表](http://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python) – 2010-07-24 19:27:19
忘記我的文件= [f爲f in os.walk(rootdir)中的(subdir,dirs,files)文件]我認爲有很多副作用。我將刪除答案 – luc 2010-07-24 19:30:56