nuT707 nuT707 - 3 months ago 20
Python Question

How to open file using argparse?

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()

wim wim
Answer

The type of the argument should be string (which is default anyway). So make it like this:

parser = argparse.ArgumentParser()
parser.add_argument('filename')
args = parser.parse_args()
with open(args.filename) as file:
  # do stuff here
Comments