+4 votes
in Programming Languages by (74.2k 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 (349k 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'):
        files.append(file)
print(files)

Using the module glob

import glob
import os
os.chdir('path/to/your/directory')
files = glob.glob('*.py')
print(files)


...