Search code examples
pythonpython-3.xenvironment-variablescredentials

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


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!


Solution

  • 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.