是否可以使用os.listdir命令查看具有特定扩展名的文件?我希望它可以工作,以便它可以只显示文件或文件夹与.f结尾。我检查了文档,什么也没找到,所以别问了。
发布于 2010-06-26 10:50:07
glob擅长这一点:
import glob
for f in glob.glob("*.f"):
print(f)发布于 2010-06-26 10:45:50
别问什么?
[s for s in os.listdir() if s.endswith('.f')]如果你想检查扩展列表,你可以做一个明显的泛化,
[s for s in os.listdir() if s.endswith('.f') or s.endswith('.c') or s.endswith('.z')]或者用另一种方式编写会稍微短一些:
[s for s in os.listdir() if s.rpartition('.')[2] in ('f','c','z')]发布于 2010-06-26 16:06:14
到目前为止还没有提到另一种可能性:
import fnmatch
import os
for file in os.listdir('.'):
if fnmatch.fnmatch(file, '*.f'):
print file实际上,这就是glob模块的实现方式,所以在这种情况下,glob更简单、更好,但fnmatch模块在其他情况下也很方便,例如,当使用os.walk进行树遍历时。
https://stackoverflow.com/questions/3122514
复制相似问题