Challenge: Given a string
'/path/to/file.py'. How to check whether a file exists at
'/path/to/file.py', without using the
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,
from pathlib import Pathto import the path object,
- Create a path object with
- Run its
.is_file()method that returns
Trueif the file exists and
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.
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.