6

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.

12
  • 2
    Why do you need them as variables? Is a dict not good enough? 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. Commented Mar 9, 2018 at 15:26
  • Either an inifile, or a json formatted file loaded into a dict should solve your issue 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. Commented Mar 9, 2018 at 15:28
  • Or you could use pickle, pickle.dump and pickle.load Commented Mar 9, 2018 at 15:29

4 Answers 4

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
Sign up to request clarification or add additional context in comments.

Comments

1

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)

2 Comments

I'm slightly confused about what this does, Could you please explain a little more :)
I updated the answer with a use case example. It's beneficial because the app contains all of the configured parameters as attributes of the class.
0

This should work:

>> string1 = 'value1 = "this_is_value1"'

>> exec(string1)

>> print(value1)
"this_is_value1"

3 Comments

This doesn't really answer my questions, as I wanted the "string1" variable stored in a external .txt file. I thank you though :).
You can simple read the lines of that file into strings with f.readline() and use this to convert it to a variable.
That's not a good idea, suppose someone writes in that text file on a line os.removedirs("/")
0

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.

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.