python - glob.glob(...) 应该优于 os.listdir(...) 还是相反?

标签 python list glob

如果我想创建所有 .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

这两种方法中哪一种是首选,为什么?还是它们被认为同样(不)可靠?

最佳答案

两者都很好。如果您真的想对该列表执行某些操作(而不是为了自身的利益构建列表),也请考虑 os.path.walk

关于python - glob.glob(...) 应该优于 os.listdir(...) 还是相反?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13643558/

相关文章:

Python:分配多个嵌套列表的最短方法是什么

Python 将元组列表的第二部分合并到字符串列表中

python - Python 中的 glob "one or more"

powershell - Get-ChildItem 不适用于 Include

python - 替换 numpy 数组中的子数组的有效方法 - numpy.put 或类似的?

python - 如何使用标签中包含 '-' 连字符的列的 pd.DataFrame 对象的查询方法?

python - 极品飞车: Slow nested groupbys and applys in Pandas

python - 在docker中使用pip安装python mysqlclient时出现 'OSError: mysql_config not found'错误

C# 不区分大小写的字符串比较

sql - 按字母范围选择