【问题标题】:How can I update a specific value on a custom configuration file?如何更新自定义配置文件上的特定值?
【发布时间】:2016-11-06 16:05:00
【问题描述】:

假设我有一个包含此内容的配置 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 新手)

【问题讨论】:

    标签: python configuration-files


    【解决方案1】:

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

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

    但请注意,json dict 没有顺序。 所以不保证元素的顺序(通常不需要)json 列表有顺序。

    【讨论】:

      【解决方案2】:

      你可以这样做:

      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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-07-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-08
        • 2012-01-11
        相关资源
        最近更新 更多