因此:
Lucy:4
Henry:8
Henry:9
Lucy:9
至此
Lucy: 4,9
Henry: 8,9
这个问题现在已经解决了,谢谢
最佳答案
非常直接的解决方案可能是这样的:(如果您不想使用defaultdict)
with open('input.txt') as f:
dic = {}
for line in f:
key,value = line.strip().split(':')
dic.setdefault(key,[]).append(value)
with open('output','a') as f:
for key,value in dic.items():
f.write(key + ':' + ','.join(value) + '\n')
更新
我已经修复了您的代码,您需要更改此行:
删除以下几行,它们在这里没有用。
file = open(class_number, 'a') #opens the file in 'append' mode so you don't delete all the information file.write(str(name + ",")) #writes the name and ":" to file file.write(str(score)) #writes the score to file file.write('\n')#writes the score to the file file.close()#safely closes the file to save the information
您使用了错误的分隔符。
key,value= line.split(",")
将其更改为以下内容:
key,value= line.strip().split(":")
这将修复您的错误。
注意这里,strip() 用于删除空格和换行符。
不太清楚,为什么要打印逗号。
file.write(key + ':' + ',' + ',' + ','.join(value))
将其更改为以下内容:
file.write(key + ':' + ','.join(value) + '\n')
有一件事,您正在从同一个文件中读取和写入。在这种情况下,如果需要写入同一个文件,则应该一次读取所有内容。但如果您使用单独的文件,则可以使用此代码。
关于python - 检查文本文件中的列表是否已存在并向其追加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35100461/