在Python中os.walk()的奇怪行为?

时间:2012-02-29 18:25:00

标签: python os.walk

这是原始代码块及其结果:

代码:

if os.path.isdir(top):
    for root, dirs, files in os.walk(top, topdown = True):
        for dirname in dirs:
            print 'Dirname = ', os.path.join(root, dirname)

结果:

Dirname = ../output/.svn
Dirname = ../output/a random folder
Dirname = ../output/a random folder - copy
Dirname = ../output/.svn\pristine
Dirname = ../output/.svn\temp
Dirname = ../output/.svn\pristine\04
Dirname = ../output/.svn\pristine\59
Dirname = ../output/a random folder\another one inside
Dirname = ../output/a random folder\another one inside - Copy
Dirname = ../output/a random folder\another one inside - Copy (2)

现在我想忽略所有隐藏的文件夹和子文件夹。这是修改后的代码及其结果:

代码:

if os.path.isdir(top):
    for root, dirs, files in os.walk(top, topdown = True):
        for dirname in dirs:
            print 'Dirname = ', os.path.join(root, dirname)
            if dirname.startswith('.'):
                dirs.remove(dirname)

结果:

Dirname = ../output/.svn
Dirname = ../output/a random folder - copy
Dirname = ../output/a random folder\another one inside
Dirname = ../output/a random folder\another one inside - Copy
Dirname = ../output/a random folder\another one inside - Copy (2)

我不明白的是:为什么../output/a随机文件夹不再列出了?

1 个答案:

答案 0 :(得分:6)

在迭代迭代时,不应该修改它。在这种情况下,您要在dirs循环for内修改dirs

请改为尝试:

if os.path.isdir(top):
    for root, dirs, files in os.walk(top, topdown = True):
        dirs_to_ignore = []
        for dirname in dirs:
            print 'Dirname = ', os.path.join(root, dirname)
            if dirname.startswith('.'):
                dirs_to_ignore.append(dirname)
        for dirname in dirs_to_ignore:
            dirs.remove(dirname)

另请参阅:Modifying list while iterating