Python: os.listdir的替代方案/特定扩展名

13 投票
5 回答
22112 浏览
提问于 2025-04-16 00:27

用os.listdir这个命令能不能只看到某些特定后缀的文件呢?我想让它只显示那些以.f结尾的文件或文件夹。我查了文档,没找到相关信息,所以别问我。

5 个回答

2

还有一种可能性没有提到:

import fnmatch
import os

for file in os.listdir('.'):
    if fnmatch.fnmatch(file, '*.f'):
        print file

实际上,这就是glob模块的实现方式,所以在这种情况下,glob更简单、更好。不过,fnmatch模块在其他情况下也很有用,比如在使用os.walk进行树形遍历时。

21

别问什么?

[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')]
25

glob 这个工具在这方面很不错:

import glob
for f in glob.glob("*.f"):
    print(f)

撰写回答