How to Find all files in a Directory with specific extension in Python

Posted in /  

How to Find all files in a Directory with specific extension in Python
vinaykhatri

Vinay Khatri
Last updated on November 21, 2024

    Python comes with a standard module called os that is used to handle file management using Python. With the help of Python os modules, we can perform many file management tasks like creating, renaming, moving, copying, searching, and deleting files and directories. If you want to know more about Python file management with the os module then click here .

    In this tutorial, we will not be covering all the important methods of the os module. Instead, we will be using it to find specific extension files from a directory. For example, we will be writing a python script that can find all the .txt, .doc, .py, .jgeg, etc., files from a specific directory.

    Python program to find all the .txt files from a directory

    We will start with finding all the .txt files present in a specific directory. For this tutorial, I will be searching all the .txt files present in the same directory where my Python script is located and printing the complete path as an output.

    import os
    
    for file in os.listdir():
        if file.endswith(".txt"):
            print(os.path.join(os.getcwd(),file))

    Output

    C:\Users\tsmehra\Desktop\code\data.txt
    C:\Users\tsmehra\Desktop\code\external_css.txt
    C:\Users\tsmehra\Desktop\code\external_script.txt
    C:\Users\tsmehra\Desktop\code\passwords_list.txt
    C:\Users\tsmehra\Desktop\code\vulnarable_banners.txt

    The os.listdir() function will return a list of all the files and directories present in the current directory. The .endswith() is a Python string function that will check if a file ends with an extension of .txt . The os.getcwd() function returns the absolute path of the current working directory. The os.path.join() method will join the current working directory path with the file name. In the above example, I have listed all the .txt files that are present in the same directory where the Python script is located. If you want to find files of different directories there you need to change the working directory by using the os.chdir() method.

    Example

    import os
    directory = r'C:\Users\tsmehra\Documents'
    os.chdir(directory)   #change the current working directory
    for file in os.listdir():
        if file.endswith(".txt"):
            print(os.path.join(os.getcwd(),file))

    Output

    C:\Users\tsmehra\Documents\allnew.txt
    C:\Users\tsmehra\Documents\config.txt
    C:\Users\tsmehra\Documents\Python has many built.txt

    It's very important to use the r"" prefix before the directory name else we need to specify the escape characters.

    Python program to find all the Python .py files from a directory

    The program will remain the same. The only change we need to make in order to retrieve all the .py files is in the endswith() method.

    Example

    import os
    #directory = r'<mention directory path>'
    #os.chdir(directory)   #change the current working directory
    
    for file in os.listdir():
        if file.endswith(".py"):    #only python .py files
            print(os.path.join(os.getcwd(),file))

    Output

    C:\Users\tsmehra\Desktop\code\assambaly.py
    C:\Users\tsmehra\Desktop\code\attack.py
    C:\Users\tsmehra\Desktop\code\checkweather.py
    C:\Users\tsmehra\Desktop\code\client.py
    C:\Users\tsmehra\Desktop\code\colorful.py
    C:\Users\tsmehra\Desktop\code\compareimage.py
    C:\Users\tsmehra\Desktop\code\contours.py
    C:\Users\tsmehra\Desktop\code\crackpassword.py
    C:\Users\tsmehra\Desktop\code\CssJSlinks.py
    C:\Users\tsmehra\Desktop\code\dDosattqack.py
    C:\Users\tsmehra\Desktop\code\deconde.py
    C:\Users\tsmehra\Desktop\code\DecryptFile.py
    .........

    Python program to find all the Images .jpeg, .jpg, .png files from a directory

    Now let's find all the images present in a specific directory. The code will remain pretty the same as we have written for the above examples, but here will be making some changes in the conditional if statement.

    import os
    directory = r'C:\Users\tsmehra\Pictures'
    os.chdir(directory)   #change the current working directory to pictures
    
    for file in os.listdir():
        if file.split(".")[-1].lower() in ["apng", "avif", "gif","jpeg", "jpg", "png", "svg"]:
            print(os.path.join(os.getcwd(),file))

    Output

    C:\Users\tsmehra\Pictures\Armstrong_Number_Python.jpg
    C:\Users\tsmehra\Pictures\Arrays-data-structure.png
    C:\Users\tsmehra\Pictures\arrays.png
    C:\Users\tsmehra\Pictures\atom.png
    C:\Users\tsmehra\Pictures\best python libraries 2021.jpg
    C:\Users\tsmehra\Pictures\blur faces with open cv.jpg
    C:\Users\tsmehra\Pictures\choosepython.jpg
    C:\Users\tsmehra\Pictures\contours image opencv python.jpg
    C:\Users\tsmehra\Pictures\contours on the blank image.jpg
    C:\Users\tsmehra\Pictures\coolpad python online copiler.jpg

    Conclusion

    Let's sum up the above Python tutorial. In this tutorial, you learned how to find specific file extensions in Python. The module we used in our tutorial is os which is a Python standard module for file and directory management. If you are searching for the files that are present in the same directory of your Python script, then you do not need to change the working directory, but if you wish to find files from another directory there, you need to change the working directory using the os.chdir() method. The os.listdir() will list out all the directories and files present in the current working directory, and using the if statement and endswith() statement we can find the specific extension files.

    People are also reading:

    Leave a Comment on this Post

    0 Comments