How to Check If a File Exists Without Exceptions in Python
Exploring with os and the isFile function
When performing actions contingent on successful execution, variations of try/except statements are used to capture exceptions and respond accordingly. The basic premise here is leaping before looking, knowing that you have plans in place for errant actions. But what if you want to look before you leap? Specifically when working with files?
All of our solutions will use the os library and use the isfile() method, which returns True or False. The remainder is dictated by where the file to be checked exists relative to the executing file.
Guidelines for Exploration
Asking yourself the following questions will ensure a thorough search.
Is the file in the same directory?
To check for a file that exists within the same directory as the executing file, simply pass the file name to the method as a string.os.path.isfile("file_in_same_dir.py")
Is the file in a subdirectory?
If the file you are checking for is in a subdirectory of the executing file, then pass the relative path to the method.os.path.isfile("images/logo.png")
Is the file in a different directory?
If the file is in a completely different directory or you don’t want to be restricted to a relative path, pass the absolute path to the method.os.path.isfile("/var/www/html/blog/images/logo.png")