Search code examples
pythonfile-typeargparse

filetype-checking arguments passed to python script using argparse


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.


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)