对于西班牙语的代码,我很抱歉,但除此之外,您应该能够理解它的结构,我使用的是 Python 3.3.2 并在这里遇到问题。
leyendoestadisticas = open("listas\Estadisticas.txt", "r")
bufferestadisticas = leyendoestadisticas.read()
leyendoestadisticas.close()
if not '"'+user.name+'"' in bufferestadisticas: #If name is not found, do this
escribiendoestadisticas = open("listas\Estadisticas.txt", 'a')
escribiendoestadisticas.write(json.dumps([user.name, palabrasdelafrase, letrasdelafrase,
"1", user.nameColor, user.fontColor, user.fontFace, user.fontSize, message.body, room.name])+"\n")
escribiendoestadisticas.close()
else: #If name is found...
data = []
with open('listas\Estadisticas.txt', 'r+') as f:
for line in f:
data_line = json.loads(line)
if data_line[0] == user.name: #if name matches...
if data_line[9] == room.name: #And room also, then update info.
data_line[1] = int(data_line[1])+int(palabrasdelafrase)
data_line[2] = int(data_line[2])+int(letrasdelafrase)
data_line[3] = int(data_line[3])+1
data_line[4] = user.nameColor
data_line[5] = user.fontColor
data_line[6] = user.fontFace
data_line[7] = user.fontSize
data_line[8] = message.body
data_line[9] = room.name
else: #but if name is found and room doesn't matches. #PROBLEM HERE
escribiendoestadisticas = open("listas\Estadisticas.txt", 'a')
escribiendoestadisticas.write(json.dumps([user.name, palabrasdelafrase, letrasdelafrase,
"1", user.nameColor, user.fontColor, user.fontFace, user.fontSize, message.body, room.name])+"\n")
escribiendoestadisticas.close()
data.append(data_line)
break
f.seek(0)
f.writelines(["%s\n" % json.dumps(i) for i in data])
f.truncate()
它的目的是添加一个 user.name 并更新它的信息,只要该行的属性 9 匹配。如果不匹配,则使用相同的 user.name 但属性 9 的新值将新行添加到列表中。
如果属性 9 匹配,它会完美运行,但如果不匹配,它所做的是覆盖该 user.name 的现有值并从头开始计算 [1]、[2] 和 [3] 中的属性。
谢谢您的帮助。
编辑:使用答案中的信息进行更新:
else:
data = []
with open('listas\Estadisticas.txt', 'r+') as f:
lines = f.readlines()
for line in lines:
data_line = json.loads(line)
if data_line[0] == user.name:
if data_line[9] == room.name:
data_line[1] = int(data_line[1])+int(palabrasdelafrase)
data_line[2] = int(data_line[2])+int(letrasdelafrase)
data_line[3] = int(data_line[3])+1
data_line[4] = user.nameColor
data_line[5] = user.fontColor
data_line[6] = user.fontFace
data_line[7] = user.fontSize
data_line[8] = message.body
data_line[9] = room.name
data.append(data_line)
f.seek(0)
f.writelines(["%s\n" % json.dumps(i) for i in data])
f.truncate()
for line in lines:
data_line = json.loads(line)
if data_line[0] == user.name:
if not data_line[9] == room.name:
escribiendoestadisticas = open("listas\Estadisticas.txt", 'a')
escribiendoestadisticas.write(json.dumps([user.name, palabrasdelafrase, letrasdelafrase,
"1", user.nameColor, user.fontColor, user.fontFace, user.fontSize, message.body, room.name])+"\n")
escribiendoestadisticas.close()
但现在我收到错误:ValueError: I/O operation on closed file。完全迷失了。