1

I have the below code which expects 1 or more file names as arguments.

It works for one file but now the input arguments can be multiple files such as 1.json 2.json 3.json.

How can I handle this?

import sys
import os
import json

inFile = sys.argv[1]


print(inFile)

with open(inFile, 'r') as file:
    try:
        json_data = json.load(file)
    except ValueError as e:
        print "Invalid Json supplied:%s" % e
        exit(1)
    else:
        print "json file ok"
        print(json_data)

1 Answer 1

1

Since argv is a list (parsing the passed arg string is done for you), you can iterate over it, skipping argv[0] which is the program filename:

import json
import sys

for arg in sys.argv[1:]:
    with open(arg, "r") as file:
        try:
            json_data = json.load(file)
            print "json file ok"
            print json_data
        except ValueError as e:
            print "Invalid JSON supplied: %s" % e
            exit(1)

You may want to put this data into a list so you can do something with it in your program:

import json
import sys

data = []

for arg in sys.argv[1:]:
    with open(arg, "r") as file:
        try:
            data.append(json.load(file))                
        except ValueError as e:
            print "Invalid JSON supplied: %s" % e
            exit(1)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.