How to open file using argparse?

nuT707 picture nuT707 · Sep 18, 2013 · Viewed 87.7k times · Source

I want to open file for reading using argparse. In cmd it must look like: my_program.py /filepath

That's my try:

parser = argparse.ArgumentParser()
parser.add_argument('file', type = file)
args = parser.parse_args()

Answer

ilent2 picture ilent2 · Sep 18, 2013

Take a look at the documentation: https://docs.python.org/3/library/argparse.html#type

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('file', type=argparse.FileType('r'))
args = parser.parse_args()

print(args.file.readlines())