Search code examples
pythonargparse

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


Solution

  • 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.