【问题标题】:How do I replace a specific value in a list with Python JSON?如何用 Python JSON 替换列表中的特定值?
【发布时间】:2013-08-30 03:18:00
【问题描述】:

我得到了一个具有此列表结构的 .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)。

【问题讨论】:

    标签: python json file list replace


    【解决方案1】:

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

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

    【讨论】:

    • 我做错了什么,到目前为止,我遇到了诸如“ from contextlib import nested ImportError: cannot import name nested”之类的导入错误,但除此之外,我刚刚尝试了 line.replace 功能(没有'不知道它存在)并且它仍然在文本中添加一个新行而不是替换文件中的旧行,所以我得到了 2 个具有不同值的 user.names,这应该发生:( -- 来自文档 -- str .replace(old, new[, count]) 返回字符串的“副本”...不应该是副本,而是要编辑实际行:(
    • 我相信contextlib 仅适用于 Python 2.x。另外,我认为您正在混淆线条和字符串。
    【解决方案2】:

    我的方法是这样的(基于对 Stack Overflow 问题的回答 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

    【讨论】:

    • ¡是的,太棒了!这正是我需要的代码,它完美运行。我编辑了使它工作所需的内容,但是......我真的不明白它是如何工作的。例如,为什么数据值只是 [] 而里面什么都没有?还有为什么要使用 truncate 命令?
    • @Saelyth data 是一个空列表,我用来放置新值,然后 seek(0) 将光标放在文件开头并截断以更正文件大小,因为它可能有剩菜从以前的数据。 tutorialspoint.com/python/file_truncate.htm
    • @Saelyth Python 的美妙之处在于习语,您可能需要阅读完整的教程才能真正了解它。 diveintopython.netdiveintopython3.net
    • 是的,我现在可以看到,这非常棘手。 Gracias por la ayuda.
    • 然而这导致了一个新问题:stackoverflow.com/questions/18474673/…
    猜你喜欢
    • 2021-05-18
    • 2011-11-06
    • 2022-11-10
    • 2018-12-24
    • 2019-02-18
    • 2022-10-13
    • 2015-12-29
    • 2018-12-22
    • 1970-01-01
    相关资源
    最近更新 更多