Python List Files in a Directory: A Complete Guide

Posted in /  

Python List Files in a Directory: A Complete Guide
vinaykhatri

Vinay Khatri
Last updated on March 28, 2024

    In Python, we have an inbuilt module os that provides various methods and properties to perform operating system functionalities using Python code. The os module is compatible with all the popular operating systems such as Windows, Linux, and mac.

    We often work with files in Python and encounter situations where we need to list out all the files present in a directory or subdirectory. In such cases, we can use the os module's listdir() and walk() methods to list all the files. With listing files, we can also check for the files that are already present in the directory so we do not rewrite or append their data in our program.

    In this Python tutorial, we will walk through the os module's os.listdir() and os.walk() methods, and learn how we can list all files present in the directory using Python only.

    So let's get started.

    1. List Files & Folders in Python with os.listdir() method

    If you only wish to print all the files and sub-directories present in a directory or folder, then you can use the os module listdir() method. The listdir() method accepts the path value of the directory as a string value and returns a list of files and subdirectories names present in that directory.

    The list returned by the listdir() method will contain only the files and folders present in the specified directory path, it will not include the files and directories present in the sub-directories. This means the listdir() method only includes first-level files and folders.

    Syntax

    os.listdir(path)

    If we do not specify the path argument to the listdir() method, it will return a list of all files and folders where the Python program file is located. With this, we can list out all the files and folders present in the current directory.

    Example 1

    Let's list out all the files and folders present in our C:\Users\lenovo\Desktop\code directory.

    # import the os module
    import os
    
    # specify the directory path as raw string
    path = r"C:\Users\lenovo\Desktop\code"
    
    # list all the files and directories present in the specified path
    all_files = os.listdir(path)
    
    # print all the directories and files.
    for file in all_files:
        print(file)
    

    Output

    .google-cookie
    .idea
    .ipynb_checkpoints
    googletranslatortutoirial.py
    gsearch.py
    GuiPython.py
    mysqltutorialpython.py
    my_key.key
    my_locked.pdf
    my_locked.zip
    New Text Document.txt
    urlshortnerconsole.py
    vulnarable_banners.txt
    WikipediaPytho.py
    youtubeapicomments.py
    ZipExtractpassword.py
    __pycache__

    We can also use the listdir() method to check if a specific file present in our current working directory.

    Example

    # import the os module
    import os
    
    # specify the directory path as raw string
    path = r"C:\Users\lenovo\Desktop\code"
    
    # file to check
    file = "test.py"
    
    # list all the files and directories present in the specified path
    all_files = os.listdir(path)
    
    # check if the file present in the current directory
    result = file in all_files
    
    print(f"Does file {file} present in the current folder?: {result}")
    

    Output

    Does file test.py present in the current folder?: True
    

    2. List Files & Folders in Python with os.walk() method

    With os.listdir() method we can only list out the first root level files and folders present in that directory. But if we wish to print all the files and folders present in the subdirectories. The walk() function simply includes all the directories and files present in the specified path directory.

    Syntax

    walk(path, topdown=True, onerror=None, followlinks=False)

    The walk function can accept 4 argument values, which are all optional.

    path : is the string value that represents the directory path that all files and directories we want to list out. If it is not specified, the walk() function list out all the files and folders of the current directory.

    topdown : It is a boolean value. By default, its value is True, which means the walk method will scan all the directories and files from top to bottom. If we specify its value to False, the method will scan the directory from bottom to top.

    onerror : By default, its value is None. This argument accepts a function object that can raise the error and continue scanning or stop the walk method.

    followlinks : It is also a Boolean value argument whose default value is False. We can also specify it as True to visit directories pointed to by symlinks on systems that support them.

    Example

    Let's list out all the files and folders present in the directory

    C:\Users\lenovo\Desktop\code\project

    # import the os module
    import os
    
    # specify the directory path as raw string
    path = r"C:\Users\lenovo\Desktop\code\project"
    
    
    # list all the files and directories present in the specified path
    for root, directories, files in os.walk(path):
        for name in files:
            print(os.path.join(root, name))
        for name in directories:
            print(os.path.join(root, name))
    

    Output

    C:\Users\lenovo\Desktop\code\project\db.sqlite3
    C:\Users\lenovo\Desktop\code\project\docker-compose.yml
    C:\Users\lenovo\Desktop\code\project\Dockerfile
    C:\Users\lenovo\Desktop\code\project\manage.py
    C:\Users\lenovo\Desktop\code\project\requirements.txt
    C:\Users\lenovo\Desktop\code\project\app
    C:\Users\lenovo\Desktop\code\project\mysite
    C:\Users\lenovo\Desktop\code\project\app\admin.py
    C:\Users\lenovo\Desktop\code\project\app\apps.py
    C:\Users\lenovo\Desktop\code\project\app\models.py
    C:\Users\lenovo\Desktop\code\project\app\tests.py
    C:\Users\lenovo\Desktop\code\project\app\urls.py
    C:\Users\lenovo\Desktop\code\project\app\views.py
    C:\Users\lenovo\Desktop\code\project\app\__init__.py
    C:\Users\lenovo\Desktop\code\project\app\migrations
    C:\Users\lenovo\Desktop\code\project\app\__pycache__
    C:\Users\lenovo\Desktop\code\project\app\migrations\__init__.py
    C:\Users\lenovo\Desktop\code\project\app\migrations\__pycache__
    C:\Users\lenovo\Desktop\code\project\app\migrations\__pycache__\__init__.cpython-39.pyc
    C:\Users\lenovo\Desktop\code\project\app\__pycache__\admin.cpython-39.pyc
    C:\Users\lenovo\Desktop\code\project\app\__pycache__\models.cpython-39.pyc
    C:\Users\lenovo\Desktop\code\project\app\__pycache__\urls.cpython-39.pyc
    C:\Users\lenovo\Desktop\code\project\app\__pycache__\views.cpython-39.pyc
    C:\Users\lenovo\Desktop\code\project\app\__pycache__\__init__.cpython-39.pyc
    C:\Users\lenovo\Desktop\code\project\mysite\asgi.py
    C:\Users\lenovo\Desktop\code\project\mysite\settings.py
    C:\Users\lenovo\Desktop\code\project\mysite\urls.py
    

    Conclusion

    There are two methods in the Python os module to list out the folders and files present in a directory. The os.listdir() method can list only the root-level names of folders and files present in the specified directory. But with the os.walk() method, we can list out all the files and sub-directories present in the specified directory. In file management and handling, these two methods are very useful when checking for the files and folders present in the directory.

    People are also reading:

    Leave a Comment on this Post

    0 Comments