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.
After importing the library, argparse. ArgumentParser() initializes the parser so that you can start to add custom arguments. To add your arguments, use parser. add_argument() .
Parsing arguments In a script, parse_args() will typically be called with no arguments, and the ArgumentParser will automatically determine the command-line arguments from sys.argv .
nargs stands for Number Of Arguments.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With