Home > other >  Open json file from argparse parameter
Open json file from argparse parameter

Time:11-11

I have a program that accepts a filename as a parameter from the user, as in:

$ myprog -i filename

The filename is a file containing JSON data.

When I try to load the file into a JSON object such as this:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('-i', action='store')
filename = args.i

json_data = json.load(filename)

I am getting an error from Python saying:

line 316, in main
    json_data = json.load(input_file)
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/json/__init__.py", line 293, in load
    return loads(fp.read(),
AttributeError: 'str' object has no attribute 'read'

I need to "tell" Python that the passed parameter is an actual file that json.load should consume, I am not sure how to do that?

CodePudding user response:

You need an actual file object

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('-i', action='store')
filename = args.i

with open(filename) as f:
    json_data = json.load(f)

Keep in mind that the file needs to be in the same directory as the script if you aren't providing an absolute path

  • Related