VOOZH about

URL: https://www.geeksforgeeks.org/python/check-if-a-file-exists-in-python/

⇱ Check if a File Exists in Python - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Check if a File Exists in Python

Last Updated : 23 Jul, 2025

When working with files in Python, we often need to check if a file exists before performing any operations like reading or writing. by using some simple methods we can check if a file exists in Python without tackling any error.

Using pathlib.Path.exists (Recommended Method)

Starting with Python 3.4, pathlib module offers a more modern and object-oriented approach to handling file paths. We can use the Path object to check if a file exists.


Output
File does not exist

There are Other methods that we can use to check if a file exists in python are:


Using os.path.isfile()

If we want to be extra sure that the path is specifically a file (and not a directory) we can use os.path.isfile(). This method works similarly to os.path.exists() but it only returns True if the path is indeed a file and not a directory.


Output
File does not exist or is not a file

Using os.path.exists()

The os. path.exists() function is one of the easiest and most efficient ways to check if a file exists in Python. It returns True if the file exists and False if it doesn't.


Output
File does not exist

Note: This method does not differentiate between files and directory.

Using try-except block

If we want to directly attempt to open the file and handle the case where the file does not exist using a try-except block. This method is useful when we want to proceed with reading or writing to the file and catch any errors if it’s not found.


Output
File does not exist

Using os.access (Permission-Specific Check)

This method is suitable when you want to check if file exists, along with checking file-permissions (read, write, execute).


Comment