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

前端 未结 13 1996
广开言路
广开言路 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:45

    this is pretty clean. the commands come from the os library. this code will search through the current working directory and list only the specified file type. You can change this by replacing 'os.getcwd()' with your target directory and choose the file type by replacing '(ext)'. os.fsdecode is so you don't get a bytewise error from .endswith(). this also sorts alphabetically, you can remove sorted() for the raw list.

        import os
        filenames = sorted([os.fsdecode(file) for file in os.listdir(os.getcwd()) if os.fsdecode(file).endswith(".(ext)")])
    

提交回复
热议问题