重写我的分数文本文件,以确保它只有最后4个分数(python) [英] Rewriting my scores text file to make sure it only has the Last 4 scores (python)
问题描述
以前,我在SO用户的帮助下,能够找到如何在Python文档中存储最多4个键,并在字典中使用maxlength属性。
现在,我想进一步。以下是我的参与者Dave,Jack和Adam的所有最近分数的文本文件。
杰克:10
Dave:20
亚当:30
杰克:40
亚当:50
Dave:60
杰克:70
Dave:80
杰克:90
杰克:100
Dave:110
Dave:120
亚当:130
亚当:140
亚当:150
现在,我的代码让我看到Python中的最后4个分数:
import 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(\\\
+ k,.join(map(str,scores_guessed [k])))
writer = open('Guess Scores.txt' wb')
为键,值在scores_guessed.items()中:
writer.writerow([key,':',value])
显然,它会打印出以下结果f或字典:
亚当150 140 130 50
戴夫120 110 80 60
杰克100 90 70 40
然而,我想要文件以字母顺序读取最后四个结果:
亚当:150
亚当:140
亚当:130
亚当:50
Dave:120
Dave:110
Dave:80
Dave:60
杰克:100
杰克:90
杰克:70
杰克:40
我以为这个块的代码将工作:
为键,值在scores_guessed.items()中:
writer.writerow([key ,':',value])
然而这会让我得到结果:
AttributeError:'_io.BufferedWriter'对象没有属性'writerow'
例如,如果adam得分为200,我想把scores_guessed改写为:
亚当:200
亚当:150
亚当:140
A大坝:130
发生什么问题?
更新 - 为了回应下面的第一个答案,我已经编辑了最后一个代码块:
for key,values in scores_guessed.items():
writer.write({}:{} \\\
.format(key,value))
然而它给我这个消息:
writer.write({}:{} \\\
.format(key,value )
TypeError:'str'不支持缓冲区接口
发生了什么?
您使用的 writer.writerow
语法对应于 csv模块,以下列方式使用:
csvfile:
writer = csv.writer(csvfile,delimiter ='',
quotecharimport csv
with open('some_file.csv','wb' ='|' oting = csv.QUOTE_MINIMAL)
writer.writerow(['Spam'] * 5 + ['Baked Beans']
writer.writerow(['Spam','Lovely Spam','Wonderful Spam '])
在我看来,你使用了一些错误的引用,因为你不是在上面的代码中使用 csv
模块。
所以,修改你的下面的代码
为key,值在scores_guessed.items()中:
writer.writerow([key,':',value])
到此代码:
for key,values in scores_guessed.items():
output =%s:%s\\\
%(key,value)
writer.write(output)
编辑
您以二进制模式打开文件,而是使用
writer = open('Guess Scores.txt','wt')
/ pre>
为键值,在scores_guessed.items()中的值:
outpu t ={}:{} \\\
.format(key,value)
writer.write(output)
writer.close()
编辑2
使用deque,使用:
writer = open('Guess Scores.txt','wt')
,value in score_guessed.items():
output ={}:{} \\\
.format(key,','。join(map(str,scores_guessed [key])))
writer.write(output)
writer.close()
或使用: p>
with open(output.txt,wt)as f:
for key in scores_guessed:
f.write({} {}。format(key,','。join(map(str,scores_guessed [key]))))
Previously, I had - with the help of SO users - been able to find how to store a maximum of 4 keys inside a Python Document with the maxlength property inside the dictionary.Now, I want to go further. Below is a text file with all the recent scores of my participants - Dave, Jack and 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
Now, here is my code that lets me see the last 4 Scores in Python:
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])
Clearly, it will print out the following result for the dictionary:
Adam 150 140 130 50 Dave 120 110 80 60 Jack 100 90 70 40
However, I want the file to read me the last four results in alphabetical order:
Adam:150 Adam:140 Adam:130 Adam:50 Dave:120 Dave:110 Dave:80 Dave:60 Jack:100 Jack:90 Jack:70 Jack:40
I thought that this block of code would work:
for key, value in scores_guessed.items(): writer.writerow([key,':',value])
Yet this returns me the result:
AttributeError: '_io.BufferedWriter' object has no attribute 'writerow'
For instance, if adam got a score of 200, I want the scores_guessed to be rewritten as:
Adam:200 Adam:150 Adam:140 Adam:130
What is going wrong?
UPDATE - In response to the first answer below, I have edited the last code block to this:
for key, value in scores_guessed.items(): writer.write("{}:{}\n".format(key,value))
Yet it gives me this message: writer.write("{}:{}\n".format(key,value)) TypeError: 'str' does not support the buffer interface
What is happening?
解决方案The
writer.writerow
syntax you use corresponds to the csv module, which is used in the following way: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'])
It seems to me you are using some wrong reference to do this, since you are not using
csv
module in your code above.So, alter your following code
for key, value in scores_guessed.items(): writer.writerow([key,':',value])
to this code:
for key, value in scores_guessed.items(): output = "%s:%s\n" % (key,value) writer.write(output)
Edit
You are opening your file in binary mode, instead open it in text mode using
writer = open('Guess Scores.txt', 'wt') for key, value in scores_guessed.items(): output = "{}:{}\n".format(key,value) writer.write(output) writer.close()
EDIT 2
Since you use deque, use:
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()
Or use:
with open("output.txt", "wt") as f: for key in scores_guessed: f.write("{} {}".format(key, ','.join(map(str, scores_guessed[key]))))
这篇关于重写我的分数文本文件,以确保它只有最后4个分数(python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!