argparse input can be file, directory or stdin

Viewed 38

I have a program that take input from a file or stdin. It looks like:

parser = argparse.ArgumentParser()
parser.add_argument('infile', nargs='?', type=argparse.FileType('r'), default=sys.stdin)
args = parser.parse_args()

I know that the following will take file or directory as input:

parser = argparse.ArgumentParser()
parser.add_argument('infile', nargs='+', help='Path of a file or a folder of files.')
args = parser.parse_args()

full_paths = [os.path.join(os.getcwd(), path) for path in args.infile]
for path in full_paths:
    if os.path.isfile(path):
        print("File : " + path)
    if os.path.isdir(path):
        print("Directory : " + path)

How can I get any one of the three (stdin or, file or, directory) as input using argparse.

0 Answers
Related