问题
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?
回答1:
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]))))
来源:https://stackoverflow.com/questions/28507196/rewriting-my-scores-text-file-to-make-sure-it-only-has-the-last-4-scores-python