python · March 25, 2023 0

How to Check if a File Exists in Python with isFile() and exists()

Table of Content

To check if a file exists in Python, you have multiple options. Here are three common methods:

  1. Using the os.path.isfile function:

    import os.path
    
    if os.path.isfile('/path/to/file'):
       # file exists
    else:
       # file does not exist
  2. Using the pathlib.Path.is_file method:

    from pathlib import Path
    
    if Path('/path/to/file').is_file():
       # file exists
    else:
       # file does not exist
  3. Using the os.path.exists function:

    import os.path
    
    if os.path.exists('/path/to/file'):
       # file exists
    else:
       # file does not exist

Note that if you are using Python 3 with pathlib, you may find the second method easier to read and work with. Additionally, os.path.isfile and os.path.exists can also be used to check if a path exists and is a directory instead of a file via os.path.isdir.

Here’s an example using os.path.isfile to check if a file exists:

import os.path

file_path = '/path/to/file'
if os.path.isfile(file_path):
    print(f'The file {file_path} exists.')
else:
    print(f'The file {file_path} does not exist.')

This will output either "The file /path/to/file exists." or "The file /path/to/file does not exist.", depending on whether or not the file exists at the specified path.

%d bloggers like this: