Signup/Sign In
LAST UPDATED: JANUARY 6, 2020

Check if a File exists or not in Python using os.path Module

    Sometimes, we might just need to know if a specific file or directory or a path exists or not. While this can be handled using a simple try and except block in python where we can try opening a file inside the try block and handle the exception in the except block.

    But this can be achieved with the help of many functions available in python too and we will be discussing a few of them today.

    In general, it is better and safe to use a try block around the code which tries to open the file. This will handle the unexpected case where the file gets accidentally deleted, changed or moved.




    1. Using exists method from the os module

    The os path module contains a method named exists. This method checks whether or not the path or directory or file exists. If it exists, the exists method returns True and False otherwise.

    Let's see an example,

    import os
    
    path = "Path to one of your folders/file"
    os.path.exists(path)

    Output:

    True or False depending on whether the path/directory/file exists
    



    2. Using isfile method from the os module

    The isfile method is present in the os path module. This method checks whether the specific file is present in the path (which is passed as an argument to the isfile method) or not. If it exists, it returns True and False otherwise.

    Let's see an example,

    import os
    
    path = "Path to one of your folders/file"
    os.path.isfile(path)

    Output:

    True or False depending on whether the file exists in that specified path.
    



    3. Using isdir method from the os module

    The isdir method checks whether the specified path is an existing directory or not. If yes, it returns True and False otherwise.

    Let's see an example,

    import os
    path = "Path to one of your directory"
    os.path.isdir(path)
    

    Output:

    True or False depending on whether the argument supplied to it is an existing directory or not.
    



    Conclusion:

    In this post, we saw how the methods from os path module can be used to check if a specific directory/file/path exists or not.

    I love writing about Python and have more than 5 years of professional experience in Python development. I like sharing about various standard libraries in Python and other Python Modules.
    IF YOU LIKE IT, THEN SHARE IT
    Advertisement

    RELATED POSTS