【问题标题】:how to Change dictionary values in python file如何更改python文件中的字典值
【发布时间】:2014-09-11 07:55:42
【问题描述】:

假设我有一个名为 ConfigFile.py 的 python 文件,其中包含字典:

person = {
    'name'          :       'Jhon Dow',
    'address'       :       'London',
    'age'           :       26,
    'isMarried'     :       True ,
    'brothersNames' :       ['Kim' , 'David' , 'Ron']
} 

animal = {
    'type'          :       'Lion',
    'name'          :       'Simba',
    'age'           :       10,
}

现在我想将人 [name] 更改为 Dan。 但是我想把它写到py文件中。

有没有办法使用字典对象?

谢谢!

【问题讨论】:

  • 不要将你的文件命名为dict.py(如果这实际上是它的名字);稍后尝试从此文件导入时会遇到问题,因为dict 是内置函数的名称。
  • 这应该会有所帮助:stackoverflow.com/questions/11026959/…
  • 这并没有真正的帮助

标签: python file dictionary


【解决方案1】:

如果你的文件只包含字典,你可以使用 ConfigParser 模块来解决这个问题,为此你必须改变配置解析器支持的文件格式

文件:

[person]
name = Jhon Dow
address = London
age = 256
ismarried = True
brothersnames = Kim,David,Ron
age1 = 256

[animal]
type = Lion
name = Simba
age = 10

代码:

!/usr/bin/python
import ConfigParser
config = ConfigParser.RawConfigParser()
config.read("File")
# You can set the data by specifing the section,option and value
# Changes the age of person to 256
config.set("person","age","256") 
# Change the name of person to Dan
config.set("person","name","Dan") 
# Open the File and write to it, This will change the data
with open("File","wb") as configfile:
    config.write(configfile)

这样您就可以使用 ConfigParser 模块轻松访问和写入文件,有关 configparser 模块的详细说明请参阅:https://docs.python.org/2/library/configparser.html

【讨论】:

    【解决方案2】:

    最易读的方法是将其解析为 dict,然后对其进行更新并将其写入文件。

    【讨论】:

      【解决方案3】:

      嗯,这是一个非常丑陋的设计,你应该使用 json 将数据存储在外部文件中,这样就可以加载和重写它。考虑一下:

      data.json

      {
        "person": {
          "name": "Jhon Dow", 
          "address": "London", 
          "age": 26, 
          "isMarried": true, 
          "brothersNames": [
            "Kim", 
            "David", 
            "Ron"
          ]
        }, 
        "animal": {
          "type": "Lion", 
          "name": "Simba", 
          "age": 10
        }
      }
      

      现在让我们使用这段代码:

      import json
      
      with open('data.json', 'r') as f:
          data = json.load(f)
      
      data['person']['name'] = 'JSON!'
      
      with open('data.json', 'w') as f:
          json.dump(data, f, indent=2)
      

      现在让我们看一下文件:

      {
        "person": {
          "isMarried": true, 
          "age": 26, 
          "name": "JSON!", 
          "brothersNames": [
            "Kim", 
            "David", 
            "Ron"
          ], 
          "address": "London"
        }, 
        "animal": {
          "age": 10, 
          "type": "Lion", 
          "name": "Simba"
        }
      }
      

      我们的修改就在那里。键的顺序不同,如果你想保留顺序,你可以像这样改变加载部分:

      from collections import OrderedDict
      import json
      
      with open('data.json', 'r') as f:
          data = json.load(f, object_pairs_hook=OrderedDict)
      

      如果您真的想使用现在的数据结构,请使用正则表达式(但这很难看)。检查here

      【讨论】:

      • 谢谢你,很好的回答
      【解决方案4】:

      您可以使用re 拆分为两行,使用ast.literal_eval 更改为dicts

      from ast import literal_eval
      import re
      with open("my_dict.py") as f:
          lines = re.split("\s+\n",f.read().replace(" ","")) # split and remove multiple spaces 
          person = (literal_eval(lines[0].split("=")[1])) # create person dict
          animal = (literal_eval(lines[1].split("=")[1])) # create animal dict
          person["name"] = "Dan"
          with open("my_dict.py","w") as f2: # reopen file using "w" to overwrite
              f2.write("person = {}\n".format(person))
              f2.write("animal = {}".format(animal))
      

      my_dict.py 看起来像:

      person = {'isMarried': True, 'age': 26, 'name': 'Dan', 'brothersNames': ['Kim', 'David', 'Ron'], 'address': 'London'}
      animal = {'age': 10, 'type': 'Lion', 'name': 'Simba'}
      

      如果您需要再次解析它,使用这种格式会容易得多。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-02-08
        • 1970-01-01
        • 2021-10-11
        • 1970-01-01
        • 1970-01-01
        • 2019-07-17
        • 1970-01-01
        • 2022-08-03
        相关资源
        最近更新 更多