我得到一个.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”)。
我的方法是这样的(基于对堆栈溢出问题Loading and parsing a JSON file in Python的回答):
如果我把你的问题弄错了,请纠正我。
关于您使用
break
提出的问题,请检查Python break, continue and pass Statements。下面是一个可以根据需要调整的示例:
这将用文件中的bar替换子字符串foo的每个实例,即使它确实打开了文件的两倍。
相关问题 更多 >
编程相关推荐