Home » Programming » Python » Python Check File Exists

Checking If A File Exists in Python, With Examples

This article will outline several methods which can be used to check that a file exists/is readable in the Python programming language.

You may wish to check whether a file exists before reading or writing to it to reduce the number of alerts you need to display to the user or to make sure you aren’t accidentally overwriting an existing file (or a combination of both, letting the user know a file already exists and giving them a choice to overwrite it).

Using pathlib to Check if a File Exists in Python

pathlib is available in Python 3 (and can be installed in Python 2 using the Pip Package Manager).

pathlib provides a suite of useful tools for dealing with files and folders in an object-oriented manner – making file paths easy(er) to deal with in cross-platform environments.

Here’s how it’s used:

# Import the Path module from pathlib
from pathlib import Path

# Check whether a file exists
myFile = Path("/path/to/file")
if myFile.is_file():
    # The file exists (and is a file, not a directory)

# Check whether a directory exists
myDir = Path("/path/to/dir/")
if myDir.is_dir():
    # The directory exists (and is a directory, not a file)

# Check whether a path exists, be it a file or directory
myPath = Path("/path/to/something")
if myPath.exists():
    # The path exists (could be a file, could be a directory)

You can also check if a file or directory exists at a given path by trying to resolve the path with the strict option enabled.

from pathlib import Path

myFile = Path("/path/to/file")

try:
    absoluteFilePath = myFile.resolve(strict=True)
except FileNotFoundError: # Specifically catch only a FileNotFoundError
    # Nothing exists at the given path
else:
    # A file or directory exist at the given path

Resolving the path resolves any links in it to find the absolute path to the file on the filesystem. The strict option tells Python to throw a FileNotFoundError if the file is not found.

Using os.path to Check if a File Exists

The os.path module contains functions for checking whether a path exists and whether it is a file or directory, similar to pathlib. It is available in Python versions 2 and 3. It works slightly differently as it does not require creating a Path object before checking it.

# Import the os.path module
import os.path

if os.path.exists('/path/to/something'):
    # The path exists, and could be a file or directory

if os.path.isfile('/path/to/file'):
    # The file exists and is a file

if os.path.isdir('/path/to/dir/'):
    # The directory exists and is a directory

Checking if a File is Readable with os.access()

Generally, if Python can read a file to check that it exists, it can read the file. However, if you wish to check for read access specifically, you can use the os.path modules access() function. Note that this isn’t foolproof – effective permissions and other environmental conditions can fool permissions checks – sometimes, the best way to check whether you can read a file is just to read it and catch the error (as seen further on):

# Import the os.path and os.access module
import os.path 
import os.access

# Imports a special value used to test a paths readability
from os import R_OK

myFile = "/path/to/file"

assert os.path.isfile(myFile) and os.access(myFile, R_OK), \
    # File does not exist or cannot be read

Trying to Open a File and Catching any Errors

Simply trying to read the file and catching any errors has several advantages:

  • If checking permissions then reading, the file could become unreadable between those operations (by being moved, deleted, etc.)
  • It also works when writing files.
  • It can be used to check for any reason for the file operation failure.

This example uses the with statement. Usually, after using the open() statement, you would need to call the close function on the file later to ensure it is freed for later use by other processes. with takes care of this for you, freeing up the file if there is an error or when file operations are completed, automatically. Otherwise, if you forget to close the file, you may run into issues later on and do some debugging.

try:
    with open('/path/to/file') as f:
        # The file has been opened successfully
except IOError: # If you are using Python 3, you can use the FileNotFoundError instead of IOError to specifically test for the file not existing, rather than other read errors
    # The file was not accessible

Best practice, you should use a combination of the above methods; check that the file is there when the file path is known to the program, and then catch any errors when performing read/write operations. Keeping the user informed about what your program is doing to their important files is, well, important. You don’t want to overwrite someone else’s hard work!

SHARE:
Photo of author
Author
I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.

Leave a Comment