How do I check whether a file exists without exceptions?
Explanation
Here we have to check whether a file exists without exceptions
Here the reason that you are checking is, so you can do something like if file_exists: open_it().
it is always safe to use a try around the attempt to open it. So that here checking means that you open the file or you move it or something between when you check and when you try to open it.
So that if one is not planning to open the file right now, at that time you can use os.path.isfile
It will Return True
if the path is an existing regular file. And This follows symbolic links. So both islink() and isfile() can be true for the same path. This is as follows
import os.path
os.path.isfile(fname)
if you need to be sure it’s a file.
Starting with Python 3.4, the pathlib
the module offers an object-oriented approach.
from pathlib import Path
my_file = Path("/path/to/file")
if my_file.is_file():
# file exists
And if we want to check a directory. At that time use the following statements:
if my_file.is_dir():
# directory exists
We can use exists(), so that we can check whether a path object exists independently of whether is it a file or directory.
if my_file.exists():
# path exists
One can also use resolve(strict=True)
it in a try
block. This will be as follows:
try:
my_abs_path = my_file.resolve(strict=True)
except FileNotFoundError:
# doesn't exist
else:
# exists
This is how we check whether a file exists without exceptions
Also read, Write a function that takes a list of tuples as its argument