如何更新自定义配置文件的特定值?

How can I update a specific value on a custom configuration file?

假设我有一个包含以下内容的配置 txt 文件:

{"Mode":"Classic","Encoding":"UTF-8","Colors":3,"Blue":80,"Red":90,"Green":160,"Shortcuts":[],"protocol":"2.1"}

如何在不更改文件原始格式的情况下将文件中的特定值(如 "Red":90 更改为 "Red":110

我尝试过使用 configparser 和 configobj,但由于它们是为 .INI 文件设计的,所以我不知道如何让它与这个自定义配置文件一起工作。我还尝试拆分搜索我想要更改的关键字 值但无法像以前那样保存文件的行。任何想法如何解决这个问题? (我是 Python 的新手)

这看起来像 json 所以你可以:

import json

obj  = json.load(open("/path/to/jsonfile","r"))
obj["Blue"] = 10
json.dump(obj,open("/path/to/mynewfile","w"))

但请注意,json 字典没有顺序。 因此不能保证元素的顺序(通常不需要)json 列表有顺序。

你可以这样做:

import json

d = {} # store your data here

with open('config.txt','r') as f:
   d = json.loads(f.readline())

d['Red']=14
d['Green']=15
d['Blue']=20
result = "{\"Mode\":\"%s\",\"Encoding\":\"%s\",\"Colors\":%s,\
         \"Blue\":%s,\"Red\":%s,\"Green\":%s,\"Shortcuts\":%s,\
         \"protocol\":\"%s\"}"%(d['Mode'],d['Encoding'],d['Colors'],
                                d['Blue'],d['Red'],d['Green'],
                                d['Shortcuts'],d['protocol'])


with open('config.txt','w') as f:
   f.write(result)
   f.close()

print result