【问题标题】:Using python iterators to recursively list files in a folder使用python迭代器递归列出文件夹中的文件
【发布时间】:2015-06-09 14:13:56
【问题描述】:

我正在尝试使用 python 列出文件夹中的所有 TIFF 文件。我找到了this SO question的答案,并将其代码修改如下:

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 是一个模块。 glob.glob() 返回一个列表,glob.iglob() 返回一个迭代器。见docs.python.org/2/library/glob.html。
  • 谢谢大家。这很快。我会在 9 分钟内接受。

标签: python iterator generator


【解决方案1】:

你需要调用glob.iglob(方法),而不仅仅是glob(模块),像这样:

glob.iglob(os.path.join(x[0], '*.tif'))

【讨论】:

    【解决方案2】:

    另一种方法是编写一个生成器函数来生成您需要的文件路径。与您的解决方案类似,但更具可读性。

    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'))
    

    【讨论】:

      猜你喜欢
      • 2021-03-21
      • 2020-06-01
      • 1970-01-01
      • 2018-02-21
      • 2018-08-09
      • 2018-01-23
      • 2019-12-29
      • 1970-01-01
      • 2018-06-27
      相关资源
      最近更新 更多