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

Viewed 65566

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.

import os
import re

results = []

for folder in gamefolders:
    for f in os.listdir(folder):
        if re.search('.c', f):
            results += [f]

print results

How can I just get the .c files?

15 Answers

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

Here's yet another solution, using pathlib (and Python 3):

from pathlib import Path

gamefolder = "path/to/dir"
result = sorted(Path(gamefolder).glob("**.c"))

Notice the double asterisk (**) in the glob() argument. This will search the gamefolder as well as its subdirectories. If you only want to search the gamefolder, use a single * in the pattern: "*.c". For more details, see the documentation.

You can actually do this with just os.listdir

import os
results = [f for f in os.listdir(gamefolders/folder) if f.endswith('.c')]
Related