【问题标题】:Python - write/ADD a new record in file with Json formatPython - 在 Json 格式的文件中写入/添加新记录
【发布时间】:2011-10-18 20:12:16
【问题描述】:

我想在我的文件 Json 的末尾添加一条新记录,现在它包含

 {
    "1":
         { 
           "coef":987,
           "Term":
              {
                 "x1":6,"x2":0,"x3":8
              }
          }
  }

我正在像这样读取这个文件:

  try:
      json_data=open ("/home/sage/content.txt")
      data=json.load (json_data)
  except IOError:
   print "Can't open your file"

如何在文件末尾添加新记录。

【问题讨论】:

    标签: python python-3.x sage


    【解决方案1】:

    读取数据后,无法添加到文件中,需要新建一个文件(如果需要,可以使用相同的名称):

     data['added_data'] = 'some data added'
     write_file = open("/home/sage/content.txt", "w")
     write_file.write(json.dumps(data))
    

    【讨论】:

    • 他使用的是json.load 而不是json.loads 否则答案是正确的+1
    • 好的,谢谢 ;) 但我不需要添加 .read() 来读取数据,它适用于 json_data=open ("/home/sage/content.txt")跨度>
    【解决方案2】:

    如果您使用的是 python 2.5 或更新版本,您应该使用 with 处理文件的语句:

    import json
    
    with open('content.txt', 'r') as f:
        data = json.load(f)
    
    data["2"] = { 
           "coef":987,
           "Term":
              {
                 "x1":6,"x2":0,"x3":8
              }
          }
    
    with open('content.txt', 'w') as f:
        json.dump(data, f)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-26
      • 1970-01-01
      • 1970-01-01
      • 2022-11-18
      • 2019-06-09
      • 1970-01-01
      • 2017-08-28
      • 2018-05-31
      相关资源
      最近更新 更多