Python: os.listdir alternative/certain extensions

后端 未结 5 1501
梦如初夏
梦如初夏 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:43

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

提交回复
热议问题