argparse.FileType is an argparse factory used as an argument type converter. Give it a mode such as 'rt' or 'wt', and argparse validates the named file and supplies an open file handle to the program. section 6.1.1 section 13.3
Use it to move routine file handling into command-line argument parsing:
- type=argparse.FileType('rt') requires a readable text file and returns an open handle ready for reading. section 6.3.1
- type=argparse.FileType('wt') requires a writable file and returns an open handle ready for output. section 13.1.5
- Pair it with nargs='*' or nargs='+' when a command accepts multiple file arguments; argparse then provides a list of handles. section 6.3.1
- Let argparse reject invalid paths and produce a usage message, helpful error text, and a nonzero exit code. section 7.3.1
Read a file or write standard output
A word-count command can define its input like this:\n\nparser.add_argument('file', nargs='*', type=argparse.FileType('rt'), default=[sys.stdin], help='Input file(s)')\n\nThe program can iterate over args.file without calling open(). With no filenames, the default list contains sys.stdin. For output, use type=argparse.FileType('wt') and default=sys.stdout. A missing file produces an argparse error such as: `argument -f/--file: can't open 'blargh'`. section 6.1.1 section 13.3
