0

Should I be using argparse in python for file manipulation? All the examples online are about simple manipulation of the command line arguments itself. More specifically, I have 3 specific file manipulation tasks, let's call them a,b and c. For example, running

python -i input.csv -a -b

should run tasks a and b on input.csv.

If argparse is indeed suitable, how exactly should I go about doing it? My current plan is to define a custom action for each task to make the code more extendable and reusable. Any suggestions?

user1943079
  • 511
  • 6
  • 20

1 Answers1

2

Yes, you can perfectly use argparse with file names. For example:

parser = argparse.ArgumentParser()
parser.add_argument("-i", type=str, help="...")
parser.add_argument('-a', dest='task_a', action='store_true', help="...")
parser.add_argument('-b', dest='task_b', action='store_true', help="...")

parser.set_defaults(task_a=False)   
parser.set_defaults(task_b=False)

args = parser.parse_args()

file_name = args.i
# or file_name = os.path.expanduser(args.i)

if os.path.isfile(file_name):
    file = open(file_name, 'rb')
    # and now do whatever you need to do with the file
    if args.task_a:
        ...
    if args.task_b:
        ...

    file.close()
jpl
  • 367
  • 2
  • 11