How to check if file exists before opening it in Python?

In python programming, often you need to handle files and folders. Sometimes, you may need to check if file exists before opening it or performing any other operation. Using try…except is one way to handle any errors including if the file or path not exists. Here is another simple method to check if file exists. You can use the Path.is_file() method form the module pathlib to check the file if it exists or not. Here is an example:

Example to check if file exists

from pathlib import Path

file = Path("samples/app.log")

if file.is_file():
    print("\n", file.name, "exists.\n")
else:
    print("\nFile does not xists.\n")
check if file exists before opening it in Python

Reference

  • About Path.is_file() method under pathlib module at Python Docs.


Leave your thoughts...

This site uses Akismet to reduce spam. Learn how your comment data is processed.