0

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?

2
  • 1
    The error message that you show clearly does not correspond to the code that you show - the names are different and the line numbers are way off. Please read stackoverflow.com/help/minimal-reproducible-example and make sure that others can copy and paste your example and see the exact problem that you do. Commented Nov 11, 2021 at 1:36
  • 1
    That said, you should try checking the documentation. Or rather, it seems you understand that you need a have an "actual file" to read. You cannot simply "tell" Python that the passed parameter is an actual file because it isn't; it's the name of a file. So - how do you ordinarily get "an actual file", given the file name? For example, if you wanted to read from it or write to it directly with the file methods? (if you don't know these things, you should study fundamentals first before trying this project.) Commented Nov 11, 2021 at 1:39

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.