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 somethingSolution: To check whether a file exists at a given path,
β₯οΈ Info: Are you AI curious but you still have to create real impactful projects? Join our official AI builder club on Skool (only $5): SHIP! - One Project Per Month
- Run
from pathlib import Pathto import the path object, - Create a path object with
Path('/path/to/file.py'), and - Run its
.is_file()method that returnsTrueif the file exists andFalseotherwise.
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.