[英]Using python iterators to recursively list files in a folder
我正在嘗試使用python列出文件夾中的所有TIFF文件。 我找到了這個SO問題的答案,並對其代碼進行了如下修改:
import os
import glob
from itertools import chain
def list_tifs_rec(path):
return (chain.from_iterable(glob(os.path.join(x[0], '*.tif')) for x in os.walk(path)))
def concatStr(xs):
return ','.join(str(x) for x in xs)
但是當我嘗試按以下方式執行它時,出現有關'module' object is not callable
的運行時錯誤:
>>> l = list_tifs_rec("d:/temp/")
>>> concatStr(l)
Runtime error
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "<string>", line 9, in concatStr
File "<string>", line 9, in <genexpr>
File "<string>", line 6, in <genexpr>
TypeError: 'module' object is not callable
我來自C ++背景,對Python生成器不太了解。 我四處搜尋,但找不到此錯誤的詳盡示例,可能是由於其普遍性。
誰能解釋這個錯誤以及如何解決?
謝謝。
您需要調用glob.iglob
(方法),而不僅僅是glob
(模塊),如下所示:
glob.iglob(os.path.join(x[0], '*.tif'))
一種替代方法是編寫一個生成器函數,該函數生成所需的文件路徑。 與您的解決方案類似,但更具可讀性。
def foo(root, file_ext):
for dirpath, dirnames, filenames in os.walk(root):
for f_name in filenames:
if f_name.endswith(file_ext):
yield os.path.join(dirpath, f_name)
用法
for name in foo(r'folder', 'tif'):
print name
files = ','.join(foo('c:\pyProjects', 'tiff'))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.