之前,我曾经 - 在SO用户的帮助下 - 找到了如何在Python文档中最多存储4个密钥,并在字典中使用maxlength属性。
现在,我想更进一步。以下是我的参与者的所有最近分数的文本文件 - Dave,Jack和Adam。
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
现在,这是我的代码,让我看到Python中的最后4个分数:
import collections
from collections import defaultdict
scores_guessed = collections.defaultdict(lambda: collections.deque(maxlen=4))
with open('Guess Scores.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('Guess Scores.txt', 'wb')
for key, value in scores_guessed.items():
writer.writerow([key,':',value])
显然,它会打印出字典的以下结果:
Adam 150 140 130 50
Dave 120 110 80 60
Jack 100 90 70 40
但是,我希望文件按字母顺序读取最后四个结果:
Adam:150
Adam:140
Adam:130
Adam:50
Dave:120
Dave:110
Dave:80
Dave:60
Jack:100
Jack:90
Jack:70
Jack:40
我认为这段代码可行:
for key, value in scores_guessed.items():
writer.writerow([key,':',value])
然而,这让我得到了结果:
AttributeError: '_io.BufferedWriter' object has no attribute 'writerow'
例如,如果adam获得200分,我希望score_guessed被重写为:
Adam:200
Adam:150
Adam:140
Adam:130
出了什么问题?
更新 - 在回答下面的第一个答案时,我已经编辑了最后一个代码块:
for key, value in scores_guessed.items():
writer.write("{}:{}\n".format(key,value))
然而它给了我这样的信息: writer.write( “{}:{} \ n” 个.format(键,值)) TypeError:'str'不支持缓冲区接口
发生了什么事?
答案 0 :(得分:1)
您使用的writer.writerow
语法对应the csv module,其使用方式如下:
import csv
with open('some_file.csv', 'wb') as csvfile:
writer = csv.writer(csvfile, delimiter=' ',
quotechar='|', quoting=csv.QUOTE_MINIMAL)
writer.writerow(['Spam'] * 5 + ['Baked Beans'])
writer.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])
在我看来,您使用了一些错误的引用来执行此操作,因为您没有在上面的代码中使用csv
模块。
因此,请更改以下代码
for key, value in scores_guessed.items():
writer.writerow([key,':',value])
到此代码:
for key, value in scores_guessed.items():
output = "%s:%s\n" % (key,value)
writer.write(output)
<强> 修改 强>
您正在以二进制模式打开文件,而是使用
以文本模式打开它writer = open('Guess Scores.txt', 'wt')
for key, value in scores_guessed.items():
output = "{}:{}\n".format(key,value)
writer.write(output)
writer.close()
编辑2
由于您使用deque,请使用:
writer = open('Guess Scores.txt', 'wt')
for key, value in scores_guessed.items():
output = "{}:{}\n".format(key,','.join(map(str, scores_guessed[key])))
writer.write(output)
writer.close()
或使用:
with open("output.txt", "wt") as f:
for key in scores_guessed:
f.write("{} {}".format(key, ','.join(map(str, scores_guessed[key]))))