os.walk 的目录名中的空列表是什么?

What are the empty lists in dirname of os.walk?

当使用 python 3.5 os.walk() 并查看目录名输出时,我得到很多空列表(返回 [ ])。我不知道为什么。

import os
tdir = '/home/pontiac/testdir'

gen0 = os.walk(tdir)
print(next(gen0)[1])
print(next(gen0)[1])

gen1 = os.walk(tdir)

for ea in gen1:
    print(ea[1])

输出:

['t2', 't1']

[]

['t2', 't1']

[]

[]

调用os.walkreturns一个元组(dirpath, dirnames, filenames)。您打印此元组的 [1] 元素 dirnames,它是给定目录中的子目录列表。您的目录 t1t2 显然不包含任何子目录,因此列表为空。

根据 os documentation 什么 os.walk returns 是三元组 (dirpath, dirnames, filenames).

假设您有一个目录 testdir:

testdir
      |- dir1
      |    |- file3.txt
      |- dir2
      |- file1.txt
      |- file2.txt

然后遍历 os.walk('path/to/testdir') 返回的生成器将产生以下元组:

('path/to/testdir', ['dir2', 'dir1'], ['file3.txt', 'file1.txt', 'file2.txt'])
('path/to/testdir/dir2', [], [])
('path/to/testdir/dir1', [], ['file3.txt'])

由于您从 3 元组中提取第一个元素并得到空列表,这意味着这些目录中不包含子目录。

引用自Python Documentation

os.walk(top, topdown=True, onerror=None, followlinks=False)
Generate the file names in a directory tree by walking the tree either top-down or bottom-up. For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple (dirpath, dirnames, filenames).

dirpath is a string, the path to the directory. dirnames is a list of the names of the subdirectories in dirpath (excluding '.' and '..'). filenames is a list of the names of the non-directory files in dirpath. Note that the names in the lists contain no path components. To get a full path (which begins with top) to a file or directory in dirpath, do os.path.join(dirpath, name).

因为testdir只有两个空目录t1t2,所以你会得到:

>>> import os
>>> t = '/home/pontiac/testdir'
>>> for root, dirs, files in os.walk(t):
    print root, dirs, files


/home/testdir ['t1', 't2'] []
# ^rootdir     ^dirs list  ^files in rootdir 
/home/testdir/t1 [] []
/home/testdir/t2 [] []