Python: os.listdir alternative/certain extensions

后端 未结 5 1485
梦如初夏
梦如初夏 2021-01-05 05:15

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 doc

5条回答
  •  [愿得一人]
    2021-01-05 05:36

    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.

提交回复
热议问题