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

2024-05-14 23:26:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我得到一个.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这行。然而,我已经在google上搜索了两个小时,我确实做到了这一点,但是我没有找到替换数据而不是写入或追加数据的特定调用。我怎样才能解决这个问题?

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

["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”)。


Tags: 文件数据代码txt列表datetimelinenot
2条回答

我的方法是这样的(基于对堆栈溢出问题Loading and parsing a JSON file in Python的回答):

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, continue and pass Statements

下面是一个可以根据需要调整的示例:

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的每个实例,即使它确实打开了文件的两倍。

相关问题 更多 >

    热门问题