chomes
chomes

Reputation: 79

Using Path to check if file exists when running script outside of the directory

So I currently use Path to check if a file exists

from pathlib import Path

if Path("main.conf").is_file():
    pass
else:
   setup_config()

While this works as long as I'm in the directory where I'm running the script, I'd like to make it work whatever directory I'm at and just run the script. I know it doesn't work because it's expecting the main.conf to be in the directory I'm currently in but how do I tell path to only check the in the folder where the script is located in?

Upvotes: 1

Views: 965

Answers (1)

Jon Clements
Jon Clements

Reputation: 142126

You can resolve the absolute path of the script by using sys.argv[0] and then replace the name of that script with the config file to check, eg:

import sys
import pathlib

path = path.Pathlib(sys.argv[0]).resolve()
if path.with_name('main.conf').is_file():
    # ...
else:
    # ...

Although it seems like you should probably not worry about that check and structure your setup_config so it takes a filename as an argument, eg:

def setup_config(filename):
    # use with to open file here
    with open(filename) as fin:
        # do whatever for config setup

Then wrap your main in a try/except (which'll also cover file not exists/can't open file for other reasons), eg:

path = pathlib.Path(sys.argv[0]).resolve()
try:
    setup_config(path.with_name('main.conf'))
except IOError:
    pass

Upvotes: 1

Related Questions