Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/318.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/qt/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何用Python JSON替换列表中的特定值?_Python_Json_File_List_Replace - Fatal编程技术网

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

如何用Python JSON替换列表中的特定值?,python,json,file,list,replace,Python,Json,File,List,Replace,我得到了一个具有以下列表结构的.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"] 只有在

我得到了一个具有以下列表结构的.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这行。然而,我已经在谷歌上搜索了两个小时,我确实做到了这一点,但我没有找到一个具体的调用来替换数据,而不是编写或追加数据。我如何解决这个问题

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


当我想停止代码中的无限循环时,我在理解中断的作用方面也遇到了困难(昨天在程序的另一个部分中发生了这种情况,但我在JSON Python中也使用了“For line in X”)。

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

从contextlib导入嵌套
文件名='datosdeusuario.txt'
嵌套(打开(文件名为'r')、打开(文件名为'w'))为f1、f2:
对于f1中的行:
f2.写入(行.替换('foo','bar'))
这将用bar替换文件中子字符串foo的每个实例,即使它确实打开了两次文件。

我的方法是这样的(基于对堆栈溢出问题的回答):

如果我答错了你的问题,请纠正我


关于您的问题,请检查。

我做错了什么,到目前为止,我收到了导入错误,如“从contextlib导入嵌套的导入错误:无法导入嵌套的名称”,但除此之外,我只是尝试了line.replace功能(不知道它存在)它仍然在文本中添加新行,而不是替换文件中的旧行,因此我得到两个具有不同值的user.name,这应该发生:(-从documnation--str.replace(old,new[,count])返回字符串的“副本”…不应该是副本,但要编辑实际行:(我相信
contextlib
仅适用于Python 2.x。此外,我认为您混淆了行和字符串。“是的,太棒了!这正是我需要的代码,它工作得非常完美。我编辑了我需要的使其工作的内容,但是……我并不真正理解它是如何工作的。例如,为什么数据值只是[]里面什么也没有?为什么要使用truncate命令?@Saelyth data是一个空列表,我用来放置新值,然后查找(0)将光标放在文件的开头并截断以更正文件大小,因为它可能有以前数据中的剩余内容。@Saelyth Python的妙处在于习惯用法,您可能需要阅读完整的教程才能真正理解它。或者是的,我现在可以看到,这是非常棘手的。Gracias por la ayuda。然而,这导致了一个新问题:
["saelyth", "prueba", "", "2013-08-27 13:25:14"]
["saelyth", "prueba", "", "2013-08-27 13:25:32"]
["saelyth", "prueba", "", "2013-08-27 13:26:01"]
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()