【问题标题】:Using `scandir` with Python 2.7在 Python 2.7 中使用“scandir”
【发布时间】:2017-08-01 19:34:05
【问题描述】:

我希望快速构建目录中所有文件夹和子文件夹的列表,无需遍历每个子文件夹中的文件。最后一点是我不使用os.walk 的原因。为此,我遵循了一个建议使用 scandir 的示例:

import scandir
ds = scandir.scandir(datafolder)

这会产生一个scandir.ScandirIterator object。如何查看此对象,或将其视为列表?

【问题讨论】:

    标签: python-2.7 list subdirectory scandir


    【解决方案1】:

    你又回到了原点,我的朋友!要查看迭代器对象中的“数据”,您必须进行迭代。我想这样的事情会奏效,或者至少让你走上正确的道路(双关语)。

    import scandir
    ds = scandir.scandir(datafolder)    
    print [x for x in ds]
    

    【讨论】:

    • 这直接回答了我的问题,谢谢!我希望scandir 能给我datafolder 中的子文件夹,但我希望得到all 子目录。我该怎么做呢?
    • @AaronJPung 有点讽刺的是,scandir.walkscandir.walkos.walk 在功能上看起来非常相似,但是 scandir 模块声称更快,因此使用它可能比 os.walk 有一些优势
    猜你喜欢
    • 1970-01-01
    • 2012-01-18
    • 2018-07-19
    • 2012-10-08
    • 2020-02-03
    • 2019-06-02
    • 1970-01-01
    • 1970-01-01
    • 2017-11-04
    相关资源
    最近更新 更多