Alagu Jeeva
Alagu Jeeva

Reputation: 23

how to pass file as argument in python script using argparse module?

I am writing an automation script in python using argparse module in which I want to use the -s as an option which takes file/file path as an argument. Can somebody help me to do this?

Example: ./argtest.py -s /home/test/hello.txt

Upvotes: 0

Views: 10329

Answers (2)

Ren
Ren

Reputation: 2946

You can use

import argparse

parse = argparse.ArgumentParser()
parse.add_argument("-s")
args = parse.parse_args()
# print argument of -s
print('argument: ',args.s)

Suppose the above code is stored in the file example.py

$ python example.py -s /home/test/hello.txt
argument: /home/test/hello.txt

You can click here(Python3.x) or here(Python2.x) to learn more.

Upvotes: 0

zondo
zondo

Reputation: 20336

Just do this:

import argparse

parser = argparse.ArgumentParser(description="My program!", formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument("-s", type=argparse.FileType('r'), help="Filename to be passed")
args = vars(parser.parse_args())

open_file = args.s

If you want to open the file for writing, just change r to w in type=argparse.FileType('r'). You could also change it to a, r+, w+, etc.

Upvotes: 2

Related Questions