【问题标题】:Should glob.glob(...) be preferred over os.listdir(...) or the other way around?glob.glob(...) 应该优先于 os.listdir(...) 还是相反?
【发布时间】:2012-11-30 10:39:40
【问题描述】:

如果我想创建所有 .xls 文件的列表,我通常使用

rdir=r"d:\temp"
flist=[os.path.join(rdir,fil) for fil in os.listdir(rdir) if fil.endswith(".xls")]
print flist

但是,我最近看到了一个替代方法,即

rdir=r"d:\temp"
import glob
flist=glob.glob(os.path.join(rdir,"*.xls"))
print flist

这两种方法中的哪一种更受欢迎,为什么?或者他们被认为同样(不)健全?

【问题讨论】:

    标签: python list glob


    【解决方案1】:

    两者都很好。如果您真的想对该列表做一些事情(而不是为了自己的缘故构建列表),也可以考虑os.path.walk

    【讨论】:

    • 对于 python 3 它是 os.walk
    【解决方案2】:

    我个人会选择glob.glob,因为它更清楚。 但是,由于它是 listdir 的封装,因此它们都可以完成工作。

    【讨论】:

      猜你喜欢
      • 2017-09-22
      • 2017-12-23
      • 1970-01-01
      • 2011-07-25
      • 2016-06-28
      • 1970-01-01
      • 2016-02-24
      • 2011-08-13
      • 2011-02-12
      相关资源
      最近更新 更多