我正在尝试使用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'))