遍历目录会引发非迭代器错误

时间:2019-04-17 05:51:48

标签: python iterator directory subdirectory

我尝试在this page上使用确切的代码来遍历子目录。但是,出现以下错误:

  File "dir_iterator.py", line 29, in <module>
    for x in it:
TypeError: iter() returned non-iterator of type 'iterdir'

问题出在哪里,如何解决?

注意:我正在Debian Stable Linux上使用Python版本3.5.3

编辑:如@ DroidX86在下面的注释中所建议,我将逐字发布从this link复制的代码:

import os

class iterdir(object):
    def __init__(self, path, deep=False):
    self._root = path
    self._files = None
    self.deep = deep
    def __iter__(self):
    return self
    def next(self):
    if self._files:
        join = os.path.join
        d = self._files.pop()
        r = join(self._root, d)
        if self.deep and os.path.isdir(r):
        self._files += [join(d,n) for n in os.listdir(r)]
    elif self._files is None:
        self._files = os.listdir(self._root)
    if self._files:
        return self._files[-1]
    else:
        raise StopIteration


# sample:
#   a deep traversal of directories which starts with a vowel
#
it = iterdir('.')
for x in it:
    p = os.path.basename(x)
    it.deep = p[0].lower() in "aeiou"
    print x

2 个答案:

答案 0 :(得分:0)

链接的代码是为python2编写的。

您正在使用python3运行。

您将不得不更改代码以使其在python3中工作,或者可以使用python2。

答案 1 :(得分:0)

该代码是为python2编写的。出于任何原因,如果希望它与python3一起运行,请将def next:更改为def __next__:,将print x更改为print(x)。要将链接中的python2代码转换为python3,需要进行这两项更改。

import os


class iterdir(object):
    def __init__(self, path, deep=False):
        self._root = path
        self._files = None
        self.deep = deep

    def __iter__(self):
        return self

    def __next__(self):
        if self._files:
            join = os.path.join
            d = self._files.pop()
            r = join(self._root, d)
            if self.deep and os.path.isdir(r):
                self._files += [join(d, n) for n in os.listdir(r)]
        elif self._files is None:
            self._files = os.listdir(self._root)

        if self._files:
            return self._files[-1]
        else:
            raise StopIteration


# sample:
#   a deep traversal of directories which starts with a vowel
#
it = iterdir('.')
for x in it:
    p = os.path.basename(x)
    it.deep = p[0].lower() in "aeiou"
    print(x)