Check if a file exists using Python

Check if a file exists using Python

Overview

Diving into the heart of Python programming, this post sheds light on a seemingly simple yet crucial task - verifying file existence. Embark on a journey filled with practical insights, where we explore tried-and-tested methods to assure your script never trips over missing files. A blend of humor and technical expertise makes this guide an essential read for developers aiming to refine their file handling skills.

To check if a file exists or not is an extremely easy task to be done in Python, but there are some tricky parts… Below is one of the possible approaches to this.

The script below to check if a file exists.

from pathlib import Path

fileName = "c:\temp\file.txt"
file = Path(fileName)
isFile = file.is_file()

The variable isFile is set to True file passed has argument exists or False if it doesn"t. The problem with this approach is, if you don"t pass the full path of the file (example: fileName = “file.txt” will return false, even if the file exists.

To use the relative path, first we need to get the directory where the script is running:

import os

base_dir = os.path.dirname(os.path.realpath(__file__))

The variable __FILE__ exists in Python and holds the reference to the script file that is being executed.

If we join the two approaches, we can implement a pseudo-retry pattern.

def checkFile(file):
    pFile   = Path(file)
    isFile  = pFile.is_file()
    if(not isFile):
        BASE_DIR = os.path.dirname(os.path.realpath(__file__))
        pFile = Path(BASE_DIR +"\\" + file)
        isFile = pFile.is_file()

    return isFile

The function above will try to verify whether the file passed via argument exists. If it doesn"t, it concatenates the path to the current script"s path and tries again.

Referência:

Translations: