File as command line argument for argparse - error message if argument is not valid

Viewed 94253

I am currently using argparse like this:

import argparse
from argparse import ArgumentParser

parser = ArgumentParser(description="ikjMatrix multiplication")
parser.add_argument("-i", dest="filename", required=True,
    help="input file with two matrices", metavar="FILE")
args = parser.parse_args()

A, B = read(args.filename)
C = ikjMatrixProduct(A, B)
printMatrix(C)

Now I would like to note, that the argument of -i should be a readable file. How can I do that?

I've tried adding type=open, type=argparse.FileType('r') and they worked, but if the file is not valid, I would like to get an error message. How can I do that?

4 Answers

Using argparse on python3.8+. This returns Pathlib.Path.

import argparse
from pathlib import Path

def validate_file(arg):
    if (file := Path(arg)).is_file():
        return file
    else:
        raise FileNotFoundError(arg)

parser = argparse.ArgumentParser()
parser.add_argument(
    "--file", type=validate_file, help="Input file path", required=True
)
args = parser.parse_args()
Related