When working with files in Python, you’ll often need to check if a file exists before you do anything else with it, such as reading from or writing to it. Luckily, the Python standard library makes this a piece of cake. Use pathlib.Path.exists(path) to check for files and directories from pathlib import Path path_exists = Path.exists("home/dir/file.txt") if path_exists: print("found it!") else: print("not found :(") Notice that path_exists will be True whether this is a file or a directory, it’s only checking if the path exists.
Python has been growing in popularity for over 20 years, and today is used by thousands of companies to deliver efficient, and reliable software.