【问题标题】:best way to get files list of big directory on python?在python上获取大目录的文件列表的最佳方法?
【发布时间】:2011-07-04 06:01:37
【问题描述】:

我有疯狂的大目录。我需要通过 python 获取文件列表。

在代码中我需要获取迭代器,而不是列表。所以这不起作用:

os.listdir
glob.glob  (uses listdir!)
os.walk

我找不到任何好的库。帮助!也许是 c++ lib?

【问题讨论】:

标签: python list memory iterator directory


【解决方案1】:

我发现这个库真的很快。
https://pypi.org/project/scandir/
我使用了这个库中的以下代码,它就像一个魅力。

def subdirs(path):
"""Yield directory names not starting with '.' under given path."""
for entry in os.scandir(path):
    if not entry.name.startswith('.') and entry.is_dir():
        yield entry.name

【讨论】:

    【解决方案2】:

    有人从包含getdents 的那篇文章中构建了一个python 模块。顺便说一句,我知道这篇文章很旧,但你可以使用scandir(我已经用 2100 万个文件的 dirs 做到了这一点)。尽管它也是一个生成器,但 Walk 太慢了,但开销太大。

    这个模块似乎是一个有趣的选择。没有使用它,但他确实基于上面引用的 800 万个文件 LS 文章。通读代码,认为这会很有趣并且使用起来更快。

    还允许您调整缓冲区,而无需直接进入 C 语言。

    https://github.com/ZipFile/python-getdents 虽然我建议阅读文档,但通过 pip 和 pypi。

    https://pypi.org/project/getdents/

    【讨论】:

      【解决方案3】:

      对于python 2.X

      import scandir
      scandir.walk()
      

      适用于 python 3.5+

      os.scandir()
      

      https://www.python.org/dev/peps/pep-0471/

      https://pypi.python.org/pypi/scandir

      【讨论】:

        【解决方案4】:

        glob.iglob 怎么样?它是迭代器 glob。

        【讨论】:

        • 它是一个隐藏在列表后面的生成器,那么为什么不直接调用该列表呢?
        【解决方案5】:

        我发现这个库很有用:https://github.com/benhoyt/scandir

        【讨论】:

          【解决方案6】:

          你应该使用生成器。这个问题在这里讨论: http://bugs.python.org/issue11406

          【讨论】:

            【解决方案7】:

            如果您的目录太大,libc readdir() 无法快速读取它,您可能需要查看内核调用 getdents() (http://www.kernel.org/doc/man-pages/online/pages/man2/getdents.2.html)。我遇到了类似的问题,并写了一篇长篇博文。

            http://www.olark.com/spw/2011/08/you-can-list-a-directory-with-8-million-files-but-not-with-ls/

            基本上,readdir() 一次只能读取 32K 的目录条目,因此如果目录中有很多文件,readdir() 将需要很长时间才能完成。

            【讨论】:

              【解决方案8】:

              http://docs.python.org/release/2.6.5/library/os.html#os.walk

              >>> import os
              >>> type(os.walk('/'))
              <type 'generator'>
              

              【讨论】:

              【解决方案9】:

              我认为使用 opendir 会起作用,并且有一个 python 包:http://pypi.python.org/pypi/opendir/0.0.1 通过 pyrex 包装它

              【讨论】:

              • 听起来不错,但无法在 windows 下安装... 文件 "c:\python26\lib\site-packages\pyrex-0.9.9-py2.6.egg\Pyrex\Distutils\extension. py", line 69, in init **kw) TypeError: unbound method __init__() must be called with Extension instance as first argument (得到 Extension instance)
              猜你喜欢
              • 2019-02-08
              • 2016-11-08
              • 2012-01-24
              • 2014-01-16
              • 1970-01-01
              • 1970-01-01
              • 2011-01-30
              • 2015-08-17
              • 2020-09-15
              相关资源
              最近更新 更多