问题
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.
回答1:
NO, it does not close the filetype object.. see this
The problem here is that FileType
may return stdin
or stdout
, 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
回答2:
Some digging in the source reveals that it doesn't close it for you. That makes sense, as it also has to open files for writing, and you probably wouldn't want it to close those.
来源:https://stackoverflow.com/questions/13736812/argumentparser-close-file-argument