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()
Solution 1:
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())
Solution 2:
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
Solution 3:
In order to have the file closed gracefully, you can combine argparse.FileType with the "with" statement
# ....
parser.add_argument('file', type=argparse.FileType('r'))
args = parser.parse_args()
with args.file as file:
print file.read()
--- update ---
Oh, @Wernight already said that in comments