Home » Find All Files with a certain Extension Present Inside a Directory using Python

Find All Files with a certain Extension Present Inside a Directory using Python

Java SE 11 Programmer II [1Z0-816] Practice Tests
1 Year Subscription
Java SE 11 Developer (Upgrade) [1Z0-817]
Spring Framework Basics Video Course
Oracle Java Certification
Java SE 11 Programmer I [1Z0-815] Practice Tests

In this example we will find all files with a certain extension in a directory using python

We have 2 examples on how to do this.

Table of Contents

Example 1

We use a for loop, you can search for files with .py extension using glob().

The * denotes all files with the given extension.

import glob, os

# folder to check
os.chdir("numpy")

# find all .py files and display
for file in glob.glob("*.py"):
    print(file)

When you run this you will see something like this depending on the folder and contents

>>> %Run findfileext1.py
numparrayarithmetic1.py
numparrayarithmetic2.py
numprandomrand.py
numpyarraycopy1.py
numpyarraycopy2.py
numpyarraycopy3.py
numpyarraylargest1.py
numpyarraylargest2.py
numpyhistrandom.py
numpylogical.py
numpylogicalnot.py
numpylogicalor.py
numpylogicalxor.py

Example 2

In this example we use the endswith() method to check for the .py extension.

We use a for loop and iterate through each file of the directory called numpy

import os

# folder to check
for file in os.listdir("numpy"):
    if file.endswith(".py"): #python file extension
        print(file) #display files

Again, same as example 1 result

>>> %Run findfileext2.py
numparrayarithmetic1.py
numparrayarithmetic2.py
numprandomrand.py
numpyarraycopy1.py
numpyarraycopy2.py
numpyarraycopy3.py
numpyarraylargest1.py
numpyarraylargest2.py
numpyhistrandom.py
numpylogical.py
numpylogicalnot.py
numpylogicalor.py
numpylogicalxor.py

You may also like

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More