You can fix that by setting the default attribute for the argument.
parser = argparse.ArgumentParser()
parser.add_argument('-al',
type = argparse.FileType('r'),
default = [ f for f in os.listdir( '.' )
if os.path.isfile( f ) and f.endswith( '.al' )],
dest = 'alphabet' )
And afterwards do your checking. That way you only have one function checking if there are more than one or none *.al files whether the argument was omitted or not.
This could, for example, be accomplished by something like this:
args = parser.parse_args()
if isinstance(args.alphabet,types.ListType):
if len(args.alphabet) != 1:
parser.error("There must be exactly one alphabet in the directory")
else:
args.alphabet = open(args.alphabet[0])
This way args.alphabet will hold an open file if there was a alphabet file specified or there is only one alphabet file in the current working directory, but will raise an error if there are more or none in the cwd.
Note:
Because we get a list if the -al
argument is omitted, argparse.FileType('r')
will not open any file.
You also have to omit nargs=1
since that would create a list containing the one opened file, the user specified in the -al
argument. Omitting this attribute will give us the raw open file, the user specified.
EDIT: You will have to import types
.