import os
source_dir = r'C:\Downloads'
ext = '.mp3'
for dirName, subdirList, fileList in os.walk(source_dir):
if not any(os.path.splitext(fileName)[1].lower() == ext for fileName in fileList):
print ' skipping "{}"'.format(dirName)
continue
else: # why is this clause needed to continue this iteration of a loop?
print 'contains "{}"'.format(dirName)
pass
print 'processing "{}" which has "{}" files'.format(dirName, ext)
解开谜题
看似奇怪的行为是由于缩进问题造成的,该问题在上面的代码中和我的文本编辑器中都不可见。原来是最后print语句缩进了 3 个空格,然后是一个制表符,这使得它看起来与 else 对齐, 但实际上它要么遵循 pass在else如果它在那里,或者跟随 continue在 if 的第一部分.显然让我很困惑。
#test1.py
import os
source_dir = '.'
ext = '.txt'
for dirName, subdirList, fileList in os.walk(source_dir):
if not any(os.path.splitext(fileName)[1].lower() == ext for fileName in fileList):
print ' skipping "{}"'.format(dirName)
continue
else: # why is this clause needed to continue this iteration of a loop?
print 'contains "{}"'.format(dirName)
pass
print 'processing "{}" which has "{}" files'.format(dirName, ext)
和
#test2.py
import os
source_dir = '.'
ext = '.txt'
for dirName, subdirList, fileList in os.walk(source_dir):
if not any(os.path.splitext(fileName)[1].lower() == ext for fileName in fileList):
print ' skipping "{}"'.format(dirName)
continue
#else: # why is this clause needed to continue this iteration of a loop?
# print 'contains "{}"'.format(dirName)
# pass
print 'processing "{}" which has "{}" files'.format(dirName, ext)