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.