【发布时间】:2015-02-13 21:06:14
【问题描述】:
我之前一直在为一个测验程序编写代码,其中包含一个存储所有参与者结果的文本文件。将文本文件转换为字典的代码和文本文件本身如下所示:
代码:
import collections
from collections import defaultdict
scores_guessed = collections.defaultdict(lambda: collections.deque(maxlen=4))
with open('GuessScores.txt') as f:
for line in f:
name,val = line.split(":")
scores_guessed[name].appendleft(int(val))
for k in sorted(scores_guessed):
print("\n"+k," ".join(map(str,scores_guessed[k])))
writer = open('GuessScores.txt', 'wb')
for key, value in scores_guessed.items():
output = "%s:%s\n" % (key,value)
writer.write(output)
文本文件如下所示:
Jack:10
Dave:20
Adam:30
Jack:40
Adam:50
Dave:60
Jack:70
Dave:80
Jack:90
Jack:100
Dave:110
Dave:120
Adam:130
Adam:140
Adam:150
现在,当我运行程序代码时,字典显示如下:
Adam 150 140 130 50
Dave 120 110 80 60
Jack 100 90 70 40
现在,这会将字典按最高分的顺序排列,然后是前 4 分!
我希望 python IDLE 将 GuessScores.txt 覆盖为:
Adam:150
Adam:140
Adam:130
Adam:50
Dave:120
Dave:110
Dave:80
Dave:60
Jack:100
Jack:90
Jack:70
Jack:40
但是当我运行代码时,出现了这个错误:
Traceback (most recent call last):
File "/Users/Ahmad/Desktop/Test Files SO copy/readFile_prompt.py", line 16, in <module>
writer.write(output)
TypeError: 'str' does not support the buffer interface
GuessScores.txt 文件是空的,因为它无法写入该文件,因为存在上述错误。
为什么会这样?解决方法是什么?我以前问过这个,但有很多问题。我在 Mac 10.8 Mavericks iMac 上运行 Python 3.3.2,如果有帮助的话。
谢谢, 德尔伯特。
【问题讨论】:
-
重复您的stackoverflow.com/questions/28520067/… 请不要再问同样的问题了。
标签: python dictionary interface buffer python-idle