0

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?

chomes
  • 59
  • 7

1 Answers1

1

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
Jon Clements
  • 138,671
  • 33
  • 247
  • 280
  • This worked perfectly, thank you :). I ended up using the first one because this file check is in my __init__ to my object. This works a perfect treat and i'll definitely remember this for future reference. Curious though doesn't pathlib have something like to grab where the user ran the command from? Not that I'm complaining about sys as it 100% works with what I need I'm just surprised pathlib doesn't have a built in function to do this. – chomes Jan 30 '20 at 12:13