Python - How To Check if a File Exists in Python

ID : 395

viewed : 85

Tags : PythonPython File

vote vote

91

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 function 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 23 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 os.path.exists() 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 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.

  • Related HOW TO?