path to a directory as argparse argument

One can ensure the path is a valid directory with something like:

import argparse, os

def dir_path(string):
    if os.path.isdir(string):
        return string
    else:
        raise NotADirectoryError(string)

parser = argparse.ArgumentParser()
parser.add_argument('--path', type=dir_path)

# ...

Check is possible for files using os.path.isfile() instead, or any of the two using os.path.exists().

Leave a Comment