argumentparser can take file type argument and leave the file open directly, for example:
parser.add_argument('infile', nargs='?', type=argparse.FileType('r'))
args = parser.parse_args().__dict__
input = args['infile'].readlines()
do I need to close args['infile'] in my program? Would argumentparser close it for me? I didn’t find anywhere mention this in the documentations.
NO, it does not close the filetype object.. see this
The problem here is that
FileTypemay returnstdinorstdout, so it can’t just always close the file object.A great number of unclosed file handles may cause problem to some OSes, but that’s it. On the plus side, the fact that argparse accepts for its type argument any callable that can check and convert a string input is simple, clean and works.
Also look at this