0

该脚本基本上是创建一个包含所有目录中所有文件的列表。知道为什么在必须扫描大于几个文件的目录时似乎会崩溃吗?

import os

correctlyNamedDirectories = []

def crawlDirectories(directory):
    for dirname, dirnames, filenames in os.walk(directory):
        for subdirname in dirnames:
            correctlyNamedDirectories.append(os.path.join(dirname, subdirname))
        for filename in filenames:
            correctlyNamedDirectories.append(os.path.join(dirname, filename))

crawlDirectories('.')

print correctlyNamedDirectories

另外,有没有更干净的方法来写这个?

4

1 回答 1

1

具有列表理解的较短方法:

correctlyNamedDirectories = [os.path.join(path, subname) for path, dirnames, filenames in os.walk(directory) for subname in dirnames + filenames]
于 2012-09-23T21:24:46.517 回答