Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Open json file from argparse parameter

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading