Python Check If File or Directory Exists

Posted in /  

Python Check If File or Directory Exists
vinaykhatri

Vinay Khatri
Last updated on March 29, 2024

    Often when we write programs for big projects there we have to deal with file management. Luckily Python comes with two powerful Standard modules os and pathlib which makes file management easy. The Python os module is generally used to interact with the operating system, but it also provides inbuilt functions related to file management. Both the Python modules os and pathlib support exists() method, to check whether a file or directory exists in the system. Here in this tutorial, we will learn all the different functions provided by Python os and pathlib modules to check if a file or directory present in the system or not.

    Python exists()

    Both os and pathlib modules provide exists() method to check if a file or directory exists or not. In os module we use the os.path.exists() and in pathlib module we use Path.exists() .

    os.path.exists()

    The os.path.exists() method is a shorthand to check if a directory or file exists in the system. This Python exists() function accepts a string value that represents the directory or file path. If the directory or file path exists in the system, the function will return the True boolean value otherwise return the false boolean value.

    Syntax

    import os 
    
    os.path.exists("diretory or file path")

    Example

    Let's say we want to check if the directory subfolder and file demo.txt exists in the C:\Users\tsmehra\dev\example directory.

    #Python program to check if a file or directory exists

    import os
    
    #check subfolder directory (True)
    print(r"Does directory C:\Users\tsmehra\dev\example\subfolder exists:")
    print(os.path.exists(r"C:\Users\tsmehra\dev\example\subfolder"))
    
    #check demo.txt file  (True)
    print(r"Does file C:\Users\tsmehra\dev\example\demo.txt exists:")
    print(os.path.exists(r"C:\Users\tsmehra\dev\example\demo.txt"))
    
    #check if demoo.txt exist (False)
    print(r"Does file C:\Users\tsmehra\dev\example\demoo.txt exists:")
    print(os.path.exists(r"C:\Users\tsmehra\dev\example\demoo.txt"))

    Output

    Does directory C:\Users\tsmehra\dev\example\subfolder exists:
    True
    Does file C:\Users\tsmehra\dev\example\demo.txt exists:
    True
    Does file C:\Users\tsmehra\dev\example\demoo.txt exists:
    False

    In the above example, you can see that when we specify the path or using the print statement, there we have used r prefix with the string. This is because we do not want Python to treat backward slash \ as the escape characters, and by specifying the r prefix we are telling Python to read the string as a raw string. If you do not specify the r prefix you will probably get the syntax error SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 18-19: truncated \UXXXXXXXX escape If you do not wish to use the r prefix, then you have to use the escape character to escape the \ backward slash. Such as:

    import os
    
    #check subfolder directory
    print("Does directory C:\\Users\\tsmehra\\dev\\example\\subfolder exists:")
    print(os.path.exists(r"C:\\Users\\tsmehra\\dev\\example\\subfolder"))

    Path.exists()

    The Path.exists() is a built-in method of pathlib module which can tell whether the specified path exists in the system or not. It is an alternative to the os.path.exists() module.

    Syntax

    from pathlib import Path
    
    Path("path of directory or file").exists()

    Similar to os.path.exists() the Path("").exists() method also accepts a string value as a parameter for the directory and file path and returns a boolean value.

    Example

    from pathlib import Path
    
    #check subfolder directory
    print(r"Does directory C:\Users\tsmehra\dev\example\subfolder exists:")
    print(Path(r"C:\Users\tsmehra\dev\example\subfolder").exists())
    
    #check demo.txt file
    print(r"Does file C:\Users\tsmehra\dev\example\demo.txt exists:")
    print(Path(r"C:\Users\tsmehra\dev\example\demo.txt").exists())
    
    #check if nonexists.txt exist
    print(r"Does file C:\Users\tsmehra\dev\example\nonexists.txt exists:")
    print(Path(r"C:\Users\tsmehra\dev\example\nonexists.txt").exists())

    Output

    Does directory C:\Users\tsmehra\dev\example\subfolder exists:
    True
    Does file C:\Users\tsmehra\dev\example\demo.txt exists:
    True
    Does file C:\Users\tsmehra\dev\example\nonexists.txt exists:
    False

    Python isfile()

    The Python isfile() function tells us whether the given path for the file exists in the system or not. Both os and pathlib modules support isfile() function, to check if the file exists or not. In os module we have os.path.isfile() method  and in pathlib module we have Path.is_file() method to check the file's existence.

    os.path.isfile()

    The os.path.isfile() method checks whether the given path for the file is correct or not, in a nutshell, it checks the existence of a file.

    syntax

    import os 
    
    os.path.isfile("file path")

    The os.path.isfile() method returns the boolean value. It will return True if the file path exists else return False.

    Example

    import os
    
    #check demo.txt file
    print(r"Does file C:\Users\tsmehra\dev\example\demo.txt exists?")
    print(os.path.isfile(r"C:\Users\tsmehra\dev\example\demo.txt"))
    
    #check nonexists file 
    print(r"Does File C:\Users\tsmehra\dev\example\nonexist exists?")
    print(os.path.isfile(r"C:\Users\tsmehra\dev\example\nonexist.txt"))

    Output

    Does file C:\Users\tsmehra\dev\example\demo.txt exists?
    True
    Does File C:\Users\tsmehra\dev\example\nonexist exists?
    False

    Note: The os.path.isfile() method only checks the file path, not the directory, if you specify the directory it will return False.

    Path.is_file()

    Similar to the os.path.isfile() method pathlib also, support Path.is_file() method to check if the given file path exists or not.

    Syntax

    Path("file path").is_file()

    The pathlib.Path("file path").is_file() method returns the boolean value True or False. If the file path is correct it will return True else False.

    Example

    from pathlib import Path
    
    #check demo.txt file
    print(r"Does file C:\Users\tsmehra\dev\example\demo.txt exists?")
    print(Path(r"C:\Users\tsmehra\dev\example\demo.txt").is_file())
    
    #check for a nonexists file (False)
    print(r"Does file C:\Users\tsmehra\dev\example\nonexists.txt exists?")
    print(Path(r"C:\Users\tsmehra\dev\example\nonexists.txt").exists())
    
    #check for directory with is_file (False)
    print(r"Does file C:\Users\tsmehra\dev\example\subfolder exists?")
    print(Path(r"C:\Users\tsmehra\dev\example\subfolder").is_file())

    Output

    Does file C:\Users\tsmehra\dev\example\demo.txt exists?
    True
    Does file C:\Users\tsmehra\dev\example\nonexists.txt exists?
    False
    Does file C:\Users\tsmehra\dev\example\subfolder exists?
    False

    Python isdir()

    The Python isdir() function is used to check whether the path for a given directory exists in the system or not. Both os and pathlib support this function. In os module, we have os.path.isdir() method to check the directory existence and in pathlib module we have pathlib.Path.is_dir() method to check the directory existence.

    os.path.isdir()

    The os.path.isdir() method accepts a string value as a path location for a directory and returns True if the path is correct or exists, else it returns False.

    Syntax

    import os
    os.path.isdir("directory path")

    Example

    import os
    
    #check for an existance directory
    print(r"Does Directory C:\Users\tsmehra\dev\example\subfolder exists?")
    print(os.path.isdir(r"C:\Users\tsmehra\dev\example\subfolder"))
    
    #check for a non-existance directory
    print(r"Does Directory C:\Users\tsmehra\dev\example\subfolder2 exists?")
    print(os.path.isdir(r"C:\Users\tsmehra\dev\example\subfolder2"))
    
    #check for a file file
    print(r"Does file C:\Users\tsmehra\dev\example\demo.txt exists?")
    print(os.path.isdir(r"C:\Users\tsmehra\dev\example\demo.txt"))

    Output

    Does Directory C:\Users\tsmehra\dev\example\subfolder exists?
    True
    Does Directory C:\Users\tsmehra\dev\example\subfolder2 exists?
    False
    Does file C:\Users\tsmehra\dev\example\demo.txt exists?
    False

    Note: The os.path.isdir() only check the directory existence for files it would return False.

    Path.is_dir()

    The Path().is_dir() is a method of pathlib module which checks if the given path for a directory is correct or not. If the given path is correct the Path().is_dir() method will return the True, else it will return False.

    Syntax

    Path("directory path").is_dir()

    Example

    from pathlib import Path
    
    #check an existance directory
    print(r"Does directory C:\Users\tsmehra\dev\example\subfolder exists?")
    print(Path(r"C:\Users\tsmehra\dev\example\subfolder").is_dir())
    
    #check for a nonexists directory 
    print(r"Does directory C:\Users\tsmehra\dev\example\subfolder2 exists?")
    print(Path(r"C:\Users\tsmehra\dev\example\nonexists.txt").is_dir())
    
    #check an existance file
    print(r"Does file C:\Users\tsmehra\dev\example\demo.txt exists:")
    print(Path(r"C:\Users\tsmehra\dev\example\demo.txt").is_dir())

    Output

    Does directory C:\Users\tsmehra\dev\example\subfolder exists?
    True
    Does directory C:\Users\tsmehra\dev\example\subfolder2 exists?
    False
    Does file C:\Users\tsmehra\dev\example\demo.txt exists:
    False

    Summary

    Methods OS Pathlib Description
    exists os.path.exists("path") pathlib.Path("path").exists() It checks whether the given path for the directory or file exists or not.
    file exists os.path.isfile("file path") pathlib.Path("file path").is_file() It checks whether the given file path for the file exists or not.
    directory exists os.path.isdir("dir path") pathlib.Path("dir path").is_dir() It checks whether the given dir path for the directory exists or not.

    Conclusion

    With os and pathlib Python modules you can perform simple and complex file operations. So which one is better? It generally depends on the use case, The os module can be used for all operating system related task and the pathlib module can only be used for file management. If your project is already complicated and you just want to use a Python module for file management then you should use the Python pathlib module. But if you want to go deep into the operating system then you should be using os module. Performance-wise pathlib module is a little bit faster than os module.

    People are also reading:

    Leave a Comment on this Post

    0 Comments