In this tutorial we will learn how to check if a file exists without exception
You’re checking is so you can do something like if file_exists: open_it(), it’s safer to use a try around the attempt to open it. Checking and then opening risks the file being deleted or moved or something between when you check and when you try to open it.
If you’re not planning to open the file immediately, you can use os.path.isfile
import os.path
os.path.isfile(fname)
if you need to be sure it’s a file.
from pathlib import Path
my_file = Path("/path/to/file")
if my_file.is_file():
## file exists
To check a directory, do:
if my_file.is_dir():
## directory exists
To check whether a Path
object exists independently of whether is it a file or directory, use exists()
:
if my_file.exists():
## path exists
You can also use resolve(strict=True)
in a try
block:
try:
my_abs_path = my_file.resolve(strict=True)
except FileNotFoundError:
## doesn't exist
else:
## exists
#python