Check if a File Exists in Python

Jinku Hu Jan 30, 2023 Jul 29, 2018 Python Python File
  1. try...except to Check the File Existance (>Python 2.x)
  2. os.path.isfile() to Check if File Exists (>=Python 2.x)
  3. pathlib.Path.is_file() to Check if File Exists (>=Python 3.4)
Check if a File Exists in Python

This tutorial will introduce three different solutions to check whether a file exists in Python.

  1. try...except block to check the file existance (>=Python 2.x)
  2. os.path.isfile method to check the file existance (>=Python 2.x)
  3. pathlib.Path.is_file()check the file existance (>=Python 3.4)

try...except to Check the File Existance (>Python 2.x)

We could try to open the file and could check if file exists or not depending on whether the IOError (in Python 2.x) or FileNotFoundError (in Python 3.x) will be thrown or not.

def checkFileExistance(filePath):
    try:
        with open(filePath, 'r') as f:
            return True
    except FileNotFoundError as e:
        return False
    except IOError as e:
        return False

In the above example codes, we make it Python 2/3 compatible by listing both FileNotFoundError and IOError in the exception catching part.

os.path.isfile() to Check if File Exists (>=Python 2.x)

import os
fileName = r"C:\Test\test.txt"
os.path.isfile(fileName)

It checks whether the file fileName exists.

Warning

Some developers prefer to use the os.path.exists() method to check whether a file exists. But it couldn’t distinguish whether the object is a file or a directory.

import os
fileName = r"C:\Test\test.txt"
os.path.exists(fileName)
#Out: True
fileName = r"C:\Test"
os.path.exists(fileName)
#Out: True

Therefore, only use os.path.isfile if you want to check if the file exists.

pathlib.Path.is_file() to Check if File Exists (>=Python 3.4)

Since Python 3.4, it introduces an object-oriented method in pathlib module to check if a file exists.

from pathlib import Path

fileName = r"C:\Test\test.txt"
fileObj = Path(fileName)
fileObj.is_file()

Similarly, it has also is_dir() and exists() methods to check whether a directory or a file/directory exists.

Author: Jinku Hu
Jinku Hu avatar Jinku Hu avatar

Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.

LinkedIn

Related Article - Python File

  • Get All the Files of a Directory
  • Append Text to a File in Python
  • Find Files With a Certain Extension Only in Python
  • Read Specific Lines From a File in Python
  • Check if File Is Empty in Python