How to Check If a File or Directory Exists in Python?

Posted in

How to Check If a File or Directory Exists in Python?

Vinay Khatri
Last updated on May 5, 2023

    Using Python programming , we can create new directories in the memory, and in some scenarios, we may want to check if the directory that we are about to create is already present in the memory or not.

    Here, we will discuss how to check if a file or directory exists in Python. While writing a program , you might require information related to the files and directories present in the memory. Maybe you want to make sure that a data file is present in the memory, or you want to prevent file overwriting. So, let's know how to check if a file or directory already exists in Python.

    How to Check If a File or Directory Exists in Python?

    In Python, we have several methods to check whether a file or directory exists in the memory or not. Following are the three major techniques to do so:

    1. Using the OS module
    2. With file handling techniques (Can only be used for checking the existence of files)
    3. Using the pathlib module (Python 3.4 and above)

    1. Check If a File or Directory Exists in Python Using the OS Module

    The creation of files and directories in a system is managed by the operating system, and the Python os module helps us to interact with the system's operating system. In the os module, we have three methods to check the existence of a file or directory. These are isfile(), isdir(), and exists().

    • Iisfile()

    The isfile() method accepts a path as an argument and returns the result in a Boolean value. If the path given to the method consists of a file, then it will return True, else it returns False .

    Example

    from os import path
    
    if path.isfile("PASS.txt"):    #this will check for the PASS.txt file in the same folder where the program source file is present.
        print("File Found")
    else:
        print("File not found")

    Output

    File Found
    • isdir()

    The isdir() method is used to check whether the directory is present in the memory or not. Like the isfile() method, isdir() takes an argument and returns a Boolean value, i.e., True or False .

    Example

    from os import path
    
    #here in the path, we have used double backslash (//). The first backslash is for character escape, and the second backslash is for the directory separator.
    if path.isdir("C:\\Users\\Public"):
        print("This path is correct and we have this directory.")
    else:
        print("Directory not found.")

    Output

    This path is correct and we have this directory.
    • exits()

    The exists() method is another method to check whether the specified path already exists or not. With the help of this method, we can check for the existence of both directories and files.

    Example

    from os import path
    if path.isdir("C:\\Users\\Public"):
        print("This path exists.")
    else:
        print("There is no such path.")

    Output

    This path exists.

    2. Check If a File Exists in Python Using File Handling

    With the help of file handling, we can check for the existence of a file in the memory. This is one of the simplest ways to check for the existence of files as it does not require any modules. However, it can't be used for checking the existence of directories.

    Example

    try:
        with open("C:\\Users\\Public\\Downloads"):
            print("File exists.")
    except:
        print("File does not exist.")

    Output

    File does not exist.

    3. Check If a File or Directory Exists in Python Using the pathlib Module

    Only Python 3.4 and above versions have the pathlib module, and it is used to interact with the system path for file management. It provides an object-oriented interface and abstraction to interact with the system path. Similar to the os module, the pathlib module has the Path() method that can be used to check the existence of a file or directory.

    Example

    >>> import pathlib
    >>> path = pathlib.Path(Pass.txt')
    >>> path.exists()
    True
    >>> path.is_file()                              #to check whether it is a file or not
    True

    Conclusion

    For most of the cases when we deal with the operating system or file management, we use the python os module. The pathlib module is very much similar to it. The file handling technique is not that efficient because it can only be used to check the existence of a file in the directory.

    People are also reading:

    Leave a Comment on this Post

    0 Comments