Python: How can I find all files with a particular extension?

前端 未结 13 1982
广开言路
广开言路 2020-12-13 14:05

I am trying to find all the .c files in a directory using Python.

I wrote this, but it is just returning me all files - not just .c files.

13条回答
  •  星月不相逢
    2020-12-13 14:56

    There is a better solution that directly using regular expressions, it is the standard library's module fnmatch for dealing with file name patterns. (See also glob module.)

    Write a helper function:

    import fnmatch
    import os
    
    def listdir(dirname, pattern="*"):
        return fnmatch.filter(os.listdir(dirname), pattern)
    

    and use it as follows:

    result = listdir("./sources", "*.c")
    

提交回复
热议问题