[英]Create a list of all files in directory and subdirectories in python
我想提出一種列出目錄及其子目錄中所有文件的最佳方法。 完成后,我想過濾掉它們。 因此,最佳做法是分兩行完成:
def getFilesContaining(filename):
files = map(lambda x: os.path.join(x, file), os.walk('.')) #Note: this map does NOT work
filtered_files = filter(lambda x: filename in x, files)
return filtered_files
def getFilesContaining(filename):
paths = (os.path.join(root, f) for root, dirs, files in os.walk('.')
for f in files)
return (path for path in paths if filename in path)
這將返回一個迭代器。 在您的版本中, filter
返回一個列表。 如果您確實想要列表,請通過將括號(...)
替換為方括號[...]
將返回值更改為列表理解。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.