gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 12:51:49 25 4
gpt4 key购买 nike

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

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']

[]

[]

最佳答案

引自 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 [] []

关于python - os.walk 目录名中的空列表是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34556433/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com