you can directly read from args['s']
, since type=argparse.FileType('r')
. No open()
needed:
import argparse
parser = argparse.ArgumentParser(description="My program!", formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument("-s", type=argparse.FileType('r'), help="Filename/path to be passed")
args = vars(parser.parse_args())
data = args['s'].readlines()
print(data)
now you can call the script from the command prompt, e.g. as python .\test.py -s'D:/test.txt'
with test.txt containing two lines with letters 'abc':
# prints ['abc\n', 'abc\n']
edit - you can simplify the code to
parser = argparse.ArgumentParser(description="My program!", formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument("-f", type=argparse.FileType('r', encoding='UTF-8'), help="path/filename of file to be passed")
data = parser.parse_args().f.readlines()
changes:
- changed the parameter name to
f
which I find better-suited for a
filename input
- added and encoding to
type=argparse.FileType('r')
-
otherwise, it will take the OS default (e.g. on Windows: cp1252). I'd
consider it better practice to explicitly specify the encoding.
- directly accessed the
io.TextIOWrapper
with parser.parse_args().f
instead of creating a dict object first with vars()