我很抱歉用西班牙语编写的代码,但除此之外,您应该能够理解它的结构,我使用的是python3.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()
它的目的是添加用户名只要行的属性9匹配,就更新它的信息。如果不匹配,则在列表中添加一个新行用户名但是属性9的新值。在
如果属性9匹配,那么它工作得很好,但是如果不匹配,它所做的就是重写该属性的现有值用户名从零开始计算[1]、[2]和[3]中的属性。在
谢谢你的帮助。在
编辑:使用答案中的信息更新:
^{pr2}$但现在我得到了错误:ValueError:对关闭的文件执行i/O操作。 完全迷失了。在
看起来您正在修改文件,同时仍在从中读取。首先完全加载文件,然后让上下文处理程序关闭文件:
正如其他人在评论中指出的那样,您可能希望在整个文件中搜索
user.name
,而不仅仅是逐行搜索。在另外,正如@abarner指出的,只需修改循环中的
data
,然后在末尾写出完整的信息集。在几点一般性意见:
当
data_line
包含少于10个项目时,您的代码无法处理这种情况。如果发生这种情况,你的程序将崩溃。最好使用
json
将整个dict
保存到文件中。这样,当您加载dict
时,您可以立即检查并访问user.name
。我建议你把user.name
作为字典的键。它可能看起来像这样(编辑:看到你想要独特的组合用户名以及房间名称)公司名称:
^{pr2}$相关问题 更多 >
编程相关推荐