繁体   English   中英

如何使用Python JSON替换列表中的特定值?

[英]How do I replace a specific value in a list with Python JSON?

我得到了一个具有以下列表结构的.txt文件:

["saelyth", "somehting here", "Not needed", "2013-08-24 14:14:47"]
["anothername", "whatever 1", "Not needed neither", "2013-08-24 15:12:26"]
["athirdone", "just an example", "of the list structure", "2013-08-24 15:12:51"]

而且,仅当在文件中找到值1时,才需要替换特定列表的第二个值。 我正在尝试的代码就是这一代码,但到目前为止,它只是将数据追加到文件中而不是替换它。

  horaactual = datetime.datetime.now()
  filename = "datosdeusuario.txt"
  leyendo = open(filename, 'r+')
  buffer = leyendo.read()
  leyendo.close()
  fechitaguardaips = str(horaactual)[:19]
  escribiendo = open(filename, 'r+')
  for line in escribiendo:
    retrieved = json.loads(line)
    if retrieved[0] == user.name:
      retrieveddata1 = "prueba"
      mythirdvalue = "not important"
      escribiendo.write(json.dumps([user.name, retrieveddata1, mythirdvalue, fechitaguardaips])+"\n")
      break
  escribiendo.close()

我猜失败是在escribiendo.write行中。 但是,我已经搜索了两个小时,并且确实做到了这一步,但是我没有找到对替换数据的特定调用,而不是编写或追加。 我该如何解决这个问题?

这就是发生的事情,不应该:(

["saelyth", "prueba", "", "2013-08-27 13:25:14"]
["saelyth", "prueba", "", "2013-08-27 13:25:32"]
["saelyth", "prueba", "", "2013-08-27 13:26:01"]

我还想了解Break的作用,因为我想停止代码中的无限循环(昨天在程序的不同部分发生了这种情况,但是我也在JSON Python中使用了“ For line in X”),所以我很难理解。

这是一个示例,您可以根据需要进行调整:

from contextlib import nested

filename = 'datosdeusuario.txt'
with nested( open(filename,'r'),open(filename,'w') ) as f1,f2:
    for line in f1:
        f2.write(line.replace('foo','bar'))

这将用文件中的bar替换子字符串foo的每个实例,即使它确实打开了文件两次。

我的方法是这样的(基于对Stack Overflow问题的回答,即在Python中加载和解析JSON文件 ):

import json

data = []
with open('text.json', 'r+') as f:
    for line in f:
        data_line = json.loads(line)
        if data_line[0] == 'saelyth' and '1' in data_line[1]:
            data_line[1] = 'new value'
        data.append(data_line)
    f.seek(0)
    f.writelines(["%s\n" % json.dumps(i) for i in data])
    f.truncate()

如果我以错误的方式收到您的问题,请纠正我。

关于带有break的问题,请检查Python break,继续并传递Statements

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM