01-23-2021, 05:56 AM
How to Check Whether a File Exists Without Exceptions?
https://www.sickgaming.net/blog/2021/01/...xceptions/
Challenge: Given a string '/path/to/file.py'
. How to check whether a file exists at '/path/to/file.py'
, without using the try
and except
statements for exception handling?
# What You Want!
if exists('/path/to/file.py'): ... # Do something
Solution: To check whether a file exists at a given path,
- Run
from pathlib import Path
to import the path object, - Create a path object with
Path('/path/to/file.py')
, and - Run its
.is_file()
method that returnsTrue
if the file exists andFalse
otherwise.
from pathlib import Path if Path('/path/to/file.py').is_file(): print('Yay')
If the file does exist, you’ll enter the if branch, otherwise you don’t enter it. This method works across all operating systems and modern Python versions.
The post How to Check Whether a File Exists Without Exceptions? first appeared on Finxter.
https://www.sickgaming.net/blog/2021/01/...xceptions/