Python: os.listdir alternative/certain extensions

若如初见. 提交于 2020-11-27 08:19:08

问题


Is it possible to see files with certain extensions with the os.listdir command? I want it to work so it may show only files or folders with .f at the end. I checked the documentation, and found nothing, so don't ask.


回答1:


glob is good at this:

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



回答2:


Don't ask what?

[s for s in os.listdir() if s.endswith('.f')]

If you want to check a list of extensions, you could make the obvious generalization,

[s for s in os.listdir() if s.endswith('.f') or s.endswith('.c') or s.endswith('.z')]

or this other way is a little shorter to write:

[s for s in os.listdir() if s.rpartition('.')[2] in ('f','c','z')]



回答3:


There is another possibility not mentioned so far:

import fnmatch
import os

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

Actually this is how the glob module is implemented, so in this case glob is simpler and better, but the fnmatch module can be handy in other situations, e.g. when doing a tree traversal using os.walk.




回答4:


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



回答5:


Try this:

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 ]


来源:https://stackoverflow.com/questions/3122514/python-os-listdir-alternative-certain-extensions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!