How do I check whether a file exists without exceptions?
Three approaches to find a file
To check whether a file exists in Python without raising exceptions, you can use the os.path module and its exists() function. This returns True if the path points to an existing file or directory, and False otherwise. Here is an example of how you can use this approach to check for a file called myfile.txt in the current directory:
Find a file using os.path.exists() in Python
import os
# Check if "myfile.txt" exists
if os.path.exists("myfile.txt"):
print("File found!")
else:
print("File not found.")
<div class="alert alert-info flex not-prose">![]()
<span class="hidden md:block">Watch a video course</span>Python - The Practical Guide</div>
You can also use the os.path module to search for a file by its name, using the os.path.isfile() function. This function returns True if the given file exists and is a regular file (as opposed to a directory, symbolic link, etc.), and False if it does not exist or is something other than a regular file. Note that os.path.isfile() returns False for directories; use os.path.exists() if you need to count directories as valid paths. Here is an example of how you can use os.path.isfile() to search for a file:
Find a file using os.path in Python
import os
# Check if "myfile.txt" is a regular file
if os.path.isfile("myfile.txt"):
print("File found!")
else:
print("File not found.")You can also use the glob module to search for files using wildcards. Note that this approach matches patterns rather than checking a single specific file, so it is better suited for finding multiple files. For example, to find all files with the .txt extension in the current directory, you could use the following code:
Find a file using the glob module in Python
import glob
# Find all files with the ".txt" extension
txt_files = glob.glob("*.txt")
# Print the names of the found files
for file in txt_files:
print(file)