+4 votes
in Programming Languages by (75.0k points)
I want to list all Python files in a directory using a Python script. How can I do it?

1 Answer

+1 vote
by (353k points)
selected by
Best answer

There are several ways to find all files with the same extension in a folder. You can use the function glob() of the module glob or the function fnmatch() of the module fnmatch.

Here are examples to show how to use these modules:

Using the module fnmatch

import fnmatch
import os
files = []
for file in os.listdir('path/to/your/directory'):
    if fnmatch.fnmatch(file, '*.py'):

Using the module glob

import glob
import os
files = glob.glob('*.py')