遍历目录会抛出非迭代器错误

Iterating through directories throws non-iterator error

我在 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

链接代码是为 python2 编写的。

您 运行 使用 python3。

要么您必须更改代码以使其在 python3 中运行,要么您可以使用 python2.

代码是为 python2 编写的。出于任何原因,如果您希望它 运行 和 python3,请将 def next: 更改为 def __next__: 并将 print x 更改为 print(x)。这两个更改需要将 link 中的 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)