Python:os.listdir替代/某些扩展

时间:2010-06-26 02:44:26

标签: python operating-system

是否可以使用os.listdir命令查看具有特定扩展名的文件?我希望它能够工作,因此最终可能只显示带有.f的文件或文件夹。我检查了文档,什么也没找到,所以不要问。

5 个答案:

答案 0 :(得分:20)

glob擅长:

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

答案 1 :(得分:9)

不要问什么?

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

答案 2 :(得分:1)

到目前为止还没有提到另一种可能性:

import fnmatch
import os

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

实际上这就是glob模块的实现方式,因此在这种情况下glob更简单,更好,但fnmatch模块在​​其他情况下可以派上用场,例如使用os.walk进行树遍历时。

答案 3 :(得分:0)

[s for s in os.listdir() if os.path.splitext(s) == 'f']

答案 4 :(得分:0)

试试这个:

from os import listdir

extension = '.wantedExtension'

mypath = r'my\path'

filesWithExtension = [ f for f in listdir(mypath) if f[(len(f) - len(extension)):len(f)].find(extension)>=0 ]