Question

Right now i am working with a file .txt with this information:

["corrector", "Enabled"]
["Inteligencia", "Enabled"]

Then in my python program it loads that data at the very beggining, this way:

for line in open("menu.txt", 'r'):
  retrieved = json.loads(line)
  if retrieved[0] == "corrector":
    corrector = retrieved[1]
  if retrieved[0] == "Inteligencia":
    Inteligencia = retrieved[1]

So far it works perfect, however as this is for a chat bot, i want to make possible to change the value of that variables directly from the chat, and i tried this code when i call "!Enable corrector" from the chat.

  if corrector == "Enabled":
    room.message("ERROR: Already Enabled")
  else:
    data = []
    with open('menu.txt', 'r+') as f:
      for line in f:
        data_line = json.loads(line)
        if data_line[0] == "corrector": 
          data_line[1] = "Enabled"
        data.append(data_line)
      f.seek(0)
      f.writelines(["%s\n" % json.dumps(i) for i in data])
      f.truncate()
    room.message("corrector enabled")

That also works, and if i open the .txt file i can see the value it's already changed. The real problem is that python didn't seem to accept that i changed a variable, and it still thinks it's "disabled" while it's already "enabled". It won't read the variable as "enabled" until i restart the program.

I was wondering if there is a refresh option for variables or a workaround to change the value of a variables on the fly and make the effect lasts without a restart.

Was it helpful?

Solution

change the value of a variables on the fly

This code changes the value of a variable on the fly:

a = 1
a = 2

Your question suggests that you want to be able to look up a value by a calculated name. The solution is to use a dict:

mydict = {'corrector':0}
mydict['corrector'] = 1

If you want to change the values in the file, you'll need to write out a new file based on the data you have. It looks like you're loading json, so the json module will help you out with that.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top