The type argument will accept any callable which will take the string used on the command line and return some object of the desired type.
So in this case, just doing type=open would be equivalent to the action of type=file in Python 2, which is to return the handle of a file opened in read-only mode.
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('infile', type=file)
args = parser.parse_args()
print(args.infile.readline())
gives:
$ python2 test.py /etc/passwd
root:x:0:0:root:/root:/bin/bash
$ python3 test.py /etc/passwd
Traceback (most recent call last):
File "test.py", line 5, in <module>
parser.add_argument('filename', type=file)
NameError: name 'file' is not defined
After changing to type=open
$ python3 test.py /etc/passwd
root:x:0:0:root:/root:/bin/bash
(This will also work with python 2.)
However, a greater range of file opening options is available using argparse.FileType (see documentation).
This needs to be instantiated, so the basic usage is argparse.FileType(), but for example you could use argparse.FileType(mode="w") (or just argparse.FileType("w")) to get a file opened for writing. So this code:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('outfile', type=argparse.FileType(mode="w"))
args = parser.parse_args()
args.outfile.write("hello\n")
args.outfile.close()
would give this:
$ python3 test.py myoutput
$ cat myoutput
hello
although this would not be necessary for conversion of the Python 2 example in the question.
filein Python 2, either. Useargparse.FileTypeinstead.