代码之家  ›  专栏  ›  技术社区  ›  Jason Sundram Red Alert

使用os.listdir解决OSError问题

  •  11
  • Jason Sundram Red Alert  · 技术社区  · 14 年前

    ls 失败。当然,是的 os.listdir() OSError: [Errno 12] Cannot allocate memory: '.'

    人们会说“不要把那么多文件放在一个目录中!你疯了吗?”--但我喜欢假装我生活在未来,一个辉煌灿烂的地方,我有千兆字节的内存可供我使用,不需要太担心我的文件到底去了哪里,只要我的盘片上还有锈迹。

    那么,有没有好的解决办法 有问题吗?我已经考虑过了 find ,但那有点恶心,不幸的是 找到 是递归的,Mac OS X 10.6上不支持maxdepth选项。

    def ls(directory): 
        import os
        files = os.popen4('find %s' % directory)[1].read().rstrip().split('\n')
        files.remove(directory)
        return files # probably want to remove dir prefix from everything in here too
    

    更新: 操作系统列表目录() 在Python2.6中成功。

    4 回复  |  直到 14 年前
        1
  •  7
  •   Glenn Maynard    14 年前

    你在Python中碰到了一个历史工件: os.listdir os.xlistdir 已添加。

    这比在大目录上使用内存有更多的影响。即使在只有几千个文件的目录中,也必须等待整个目录扫描完成,并且必须读取 整个的 目录,即使第一个条目是您要查找的条目。

    这在Python中是一个非常明显的缺陷:似乎 opendir / readdir / fdopendir open , stat

        2
  •  4
  •   kichik    14 年前

    您可以尝试深入一层,并使用ctypes直接调用opendir()和readdir()。

        3
  •  2
  •   Jason Sundram Red Alert    14 年前
    def ls(directory): 
        """full-featured solution, via wrapping find"""
        import os
        files = os.popen4('find %s' % directory)[1].read().rstrip().split('\n')
        files.remove(directory)
        n = len(directory)
        if directory[-1] != os.path.sep:
            n += 1
        files = [f[n:] for f in files] # remove dir prefix
        return [f for f in files if os.path.sep not in f] # remove files in sub-directories
    
        4
  •  2
  •   Seth    14 年前

    我在10.6版的Apple Python 2.5.5上得到了相同的IOError,它列出了一个大目录。在Python2.6中效果很好。

    Python 2.5.5 (r255:77872, Sep 21 2010, 09:52:31) 
    [GCC 4.2.1 (Apple Inc. build 5664)] on darwin
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import os
    >>> x = os.listdir('.')
    OSError: [Errno 12] Cannot allocate memory: '.'
    

    os.listdir randomly fails on occasions when it shouldn't “和” Sloppy error checking in listdir() for Posix ".