Question

Is there a way to filetype-check filename arguments using argparse? Seems like it could be done via the type or choices keyword if I can create the right type of container object.

I'm expecting a type of file passed in (say, file.txt) and want argparse to give its automatic message if the file is not of the right type (.txt). For example, argparse might output

usage: PROG --foo filename etc... error: argument filename must be of type *.txt.

Perhaps instead of detecting the wrong filetype, we could try to detect that filename string did not end with '.txt' but that would require a sophisticated container object.

Was it helpful?

Solution

You can use the type= keyword to specify your own type converter; if your filename is incorrect, throw a ArgumentTypeError:

import argparse

def textfile(value):
    if not value.endswith('.txt'):
        raise argparse.ArgumentTypeError(
            'argument filename must be of type *.txt')
    return value

The type converter doesn't have to convert the value..

parser.add_argument('filename', ..., type=textfile)

OTHER TIPS

Sure. You can create a custom action:

class FileChecker(argparse.Action):
    def __init__(self,parser,namespace,filename,option_string=None):
        #code here to check the file, e.g...
        check_ok = filename.endswith('.txt')
        if not check_ok:
           parser.error("useful message here")
        else:
           setattr(namespace,self.dest,filename)

and then you use that as the action:

parser.add_argument('foo',action=FileChecker)

I usually use 'type' argument to do such checking

import argparse

def foo_type(path):
    if not path.endswith(".txt"):
        raise argparse.ArgumentTypeError("Only .txt files allowed")
    return path

parser = argparse.ArgumentParser()
parser.add_argument('--foo', help='foo help', type=foo_type)
args = parser.parse_args()

example:

$ python argp.py --foo not_my_type
usage: argp.py [-h] [--foo FOO]
argp.py: error: argument --foo: Only .txt files allowed
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top