d3pd
d3pd

Reputation: 8315

In Python, how should one test for the existence of a file in a path specified in an environment variable?

I want to check for the existence of the following file:

$ANALYSISDIRECTORY/data/AnalysisDerivative/configuration.txt

Currently, I have a little function to ensure that a file exists:

def ensureFileExistence(fileName):
    log.debug("ensure existence of file {fileName}".format(
        fileName = fileName
    ))
    if not os.path.isfile(fileName):
        log.info("file {fileName} does not exist\n".format(
            fileName = fileName
        ))
        sys.exit()

How should I make this function more robust and able to cope with paths and paths stored in environment variables?

Upvotes: 1

Views: 971

Answers (2)

El Bert
El Bert

Reputation: 3026

To make sure you access the value of the environment variable and not its string representation you can use os.path.expandvars

If the path you want to test is in a environment variable you can user os.getenv

Upvotes: 3

Marcus Müller
Marcus Müller

Reputation: 36346

Instead of

 if not os.path.isfile(fileName):

use

 if not os.path.exists(fileName):

Upvotes: 1

Related Questions