python argparse file extension checking

前端 未结 3 840
梦毁少年i
梦毁少年i 2021-01-03 02:25

can argparse be used to validate filename extensions for a filename cmd line parameter?

e.g. if i have a python script i run from the cmd line:

3条回答
  •  没有蜡笔的小新
    2021-01-03 02:49

    Define a custom function which takes the name as a string - split the extension off for comparison and just return the string if it's okay, otherwise raise the exception that argparse expects:

    def valid_file(param):
        base, ext = os.path.splitext(param)
        if ext.lower() not in ('.csv', '.tab'):
            raise argparse.ArgumentTypeError('File must have a csv or tab extension')
        return param
    

    And then use that function, such as:

    parser = argparse.ArgumentParser()
    parser.add_argument('filename', type=valid_file)
    

提交回复
热议问题