最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Getting Variables from a external .json file Python - Stack Overflow

programmeradmin1浏览0评论

What I need help with

I want to receive variables from a external .json file in the local directory using python27

(import doesn't work)

I want to store the variables in the .json like below

value1 = "this_is_value1"
value2 = "this_is_value2"
value3 = "this_is_value3"

and have them being used in a script.

If I can get it to the point of which the .json includes

value1 = "this_is_value1"

and my .py includes

print(value1)

with output

>>>this_is_value1

I can take it from there

My end Task

The idea is that I need to change specific parts of another .yaml file, this program needs to take variables like (ID, System_id, IP) and for this case I need a .json I can change which the python27 script then pulls the information from to change the .yaml file.

I've done this part fine, just need to do this part

Have I researched the issue?

In short, YES.

however, theses answer use .py or other file types.

I've already tried importing the file but since it needs to sit next to the script I can't use import

Other anwser simply give no information back about how they solved the issue.

What I need help with

I want to receive variables from a external .json file in the local directory using python27

(import doesn't work)

I want to store the variables in the .json like below

value1 = "this_is_value1"
value2 = "this_is_value2"
value3 = "this_is_value3"

and have them being used in a script.

If I can get it to the point of which the .json includes

value1 = "this_is_value1"

and my .py includes

print(value1)

with output

>>>this_is_value1

I can take it from there

My end Task

The idea is that I need to change specific parts of another .yaml file, this program needs to take variables like (ID, System_id, IP) and for this case I need a .json I can change which the python27 script then pulls the information from to change the .yaml file.

I've done this part fine, just need to do this part

Have I researched the issue?

In short, YES.

however, theses answer use .py or other file types.

I've already tried importing the file but since it needs to sit next to the script I can't use import

Other anwser simply give no information back about how they solved the issue.

Share Improve this question edited Apr 23, 2018 at 8:49 Teobot asked Mar 9, 2018 at 15:20 TeobotTeobot 3192 gold badges3 silver badges14 bronze badges 12
  • 2 Why do you need them as variables? Is a dict not good enough? – Norrius Commented Mar 9, 2018 at 15:26
  • 2 Have a look at the configparser module for a safe, easy way to store this kind of config. – match Commented Mar 9, 2018 at 15:26
  • Either an inifile, or a json formatted file loaded into a dict should solve your issue – Adonis Commented Mar 9, 2018 at 15:28
  • "... these answer[s] use .py or other file types" – but the methods do work? Then cheat. Rename your .txt file to .py, import, rename back. – Jongware Commented Mar 9, 2018 at 15:28
  • Or you could use pickle, pickle.dump and pickle.load – Mathieu Commented Mar 9, 2018 at 15:29
 |  Show 7 more comments

4 Answers 4

Reset to default 14

With a json formatted file (say "my_file.json"), for instance:

{
  "x": "this is x",
  "y": "this is x",
  "z": "this is z"
}

Then in Python:

import json

with open("my_file.json", "r") as f:
    my_dict = json.load(f)
print(my_dict["x"])

Yields:

this is x

I generally like to control this process with a method or function. Here is a code snip I use frequently that will read the format of the text file you've shown:

class MainApp(object):

    def __init__(self, config_file):
        # Initialization stuff from a configuration file.
        self.readConfigFile(config_file)

    def readConfigFile(self, file):
        try:
            with open(file, 'r') as cfg:
                lines = list(cfg)
            print("Read", len(lines), "lines from file", file)
            # Set configured attributes in the application
            for line in lines:
                key, value = line.split('=')
                setattr(self, key.strip(), value.strip())
        except:
            print('Configuration file read error')
            raise

if __name__ == '__main__':
    # Create an instance of the application.
    # It will read the configuration file provided here.
    app = MainApp('myconfig.txt')
    # Now you can access the attributes of the class (read from config file)
    print(app.value1, app.value2, app.value3)

This should work:

>> string1 = 'value1 = "this_is_value1"'

>> exec(string1)

>> print(value1)
"this_is_value1"

If what you really need is a .txt file, then I recommend you to take a look at the documentation: https://docs.python.org/3/tutorial/inputoutput.html Go to section: 7.2 Reading and Writing a file

Basically, you'll need is:

lines = [] # for further data manipulation
file = open("c:\path\to\your.txt", "r")
for line in file:
    lines.append([line.split("=")])
file.close()

Now if you have in your .txt bar="foo" Then in the lines list you can do:

lines[0][0] # output "bar"
lines[0][1] # output "foo"

Of course there are some more smater way of doing this, but this is just basic idea.

发布评论

评论列表(0)

  1. 暂无评论