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()
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())
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
This implementation allows the "file name" parameter to be optional, as well as giving a short description if and when the user enters the -h
or --help
argument.
parser = argparse.ArgumentParser(description='Foo is a program that does things')
parser.add_argument('filename', nargs='?')
args = parser.parse_args()
if args.filename is not None:
print('The file name is {}'.format(args.filename))
else:
print('Oh well ; No args, no problems')
I'll just add the option to use pathlib
:
import argparse, pathlib
parser = argparse.ArgumentParser()
parser.add_argument('file', type=pathlib.Path)
args = parser.parse_args()
with args.file.open('r') as file:
print(file.read())
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