Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python script open a json file with arguments

Tags:

python

I am new on python. I am using a python script where I load a json file to set certain values to the script, but my idea is to import that file more dynamically using arguments (I think is the correct use), so I don´t need to always include the name of the json file in the python script, here is may code example:

import json
from pprint import pprint

with open("VariableSettings.json") as json_data:
    data = json.load(json_data)

so my idea is to change the code: "with open("VariableSettings.json") as json_data" with args to open the json file dynamically.

I think that on command prompt I can use the command py test.py arg1 (this represent the file path).

So I know that probably my explanation is a bit confusing but if some can help I appreciate it.

like image 242
Rui Ferreira Avatar asked Feb 26 '26 01:02

Rui Ferreira


1 Answers

You can use sys to do that. In the example below I created a file test.json with the content

{"foo": "bar"}

And modified your code as

import json
import sys

with open(sys.argv[1]) as json_data:
    data = json.load(json_data)
    print(data)

You need to call execute as

python test.py test.json

and the output will be

{'foo': 'bar'}

More details can be found in this other post

like image 110
caverac Avatar answered Feb 27 '26 15:02

caverac



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!