Warm tip: This article is reproduced from stackoverflow.com, please click
credentials environment-variables python python-3.x

How to access a file a path level below from a subfolder

发布于 2020-04-05 00:26:40

Let's say I have a file called credentials.json in my current directory, an environment variable MY_CREDENTIALS=credentials.json and a script main.py that uses this environment variable via os.getenv('MY_CREDENTIALS').

Now suppose I create a subfolder and put something there like this: /subfolder/my_other_script.py. If I print os.getenv('MY_CREDENTIALS') then I get indeed credentials.json but I can't use this file as it is in my root directory (not in /subfolder). So, how can I use this file although it is in the root directory? The only thing that works for me is to make a copy of credentials.json in /subfolder, but then I would have multiple copies of this file and I don't want that.

Thanks for your response!

Questioner
math4everyone
Viewed
77
mc51 2020-02-02 21:29

Something like this could work:

from pathlib import Path
import os

FILENAME = os.getenv('MY_CREDENTIALS')
filePath = Path(FILENAME)

if filePath.exists() and filePath.is_file():
    print("Success: File exists")
    print(filePath.read_text())
else:
    print("Error: File does not exist. Getting file from level below.")
    print((filePath.absolute().parent.parent / filePath.name).read_text())

Basically, you check whether your file exists in the current folder. This will be the case, if your script is in your root folder. If it is not, you assume that you are in a subfolder. So you try to get the file from one level below (your root). It's not totally production ready, but for the specific case you mentioned it should work. In production you should think about cases where you might have nested subfolder or your file is missing for good.