怎么设置python变量_Python如何即时更改变量的值

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.

解决方案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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值