Check if a file exists using Python

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:

The following two tabs change content below.
Software Architect and Backend Developer (almost Fullstack), I usually work with C#, PowerShell, Python, Golang, bash and Unity (this one is more for a hobby). I'm always looking for something new to learn, adding new tools to my utility belt.
Posted in Python and tagged , , , .