字典无法写入文本,Python写入文本文件字典显示错误信息"/>
python空字典无法写入文本,Python写入文本文件字典显示错误信息
I'm currently testing my code to see if it functions properly, and therefore remove any inconsistencies.
First of all, the code is below:
user_name = str(input("What is your name?"))
last_name = str(input("What is your surname?"))
final_total = int(input("What is your total score?"))
with open('quiz_results.txt') as f:
for line in f:
name,val = line.split(":")
user_scores[name].appendleft(int(val))
with open("quiz_results.txt", "a+") as f:
f.write('{}:{}\n'.format(user_name + last_name, final_total))
print("complete.")
with open('quiz_results.txt') as f:
for line in f:
name,val = line.split(":")
user_scores[name].appendleft(int(val))
Now, for test data, I added 'Dave' for the user_name, 'Johnson' for the last_name and final totals were 70, 80, 90 and 100 for each go, so I repeated the program 4 times.
When I type in the first result, 70, I get the result I expect in the text file:
DaveJohnson:70
Unusually enough, in the text file, when I type in 80 for the result (with the same name) I get in the text file:
DaveJohnson:80
DaveJohnson:70
DaveJohnson:70
when I should simply get:
DaveJohnson:80
DaveJohnson:70
When I type in 90, I get in the text file:
DaveJohnson:90
DaveJohnson:70
DaveJohnson:70
when I should simply get:
DaveJohnson:90
DaveJohnson:80
DaveJohnson:70
And When I type in 100, I get in the text file:
DaveJohnson:100
DaveJohnson:70
DaveJohnson:70
BUT I should get:
DaveJohnson:100
DaveJohnson:90
DaveJohnson:80
What on Earth is going wrong?
Update It is all solved.
解决方案
You're reading quizresults.txt twice without reseting the content of user_names. So if a user name/score pair is in the file at the start you read the score into user names, then read it in again.
The content of user_scores looks like
start : {'DaveJohnson':[]} #I'm guesing
after first block on first run: {'DaveJohnson':[]}
after second block on first run: {'DaveJohnson':[0]}
after third block on first run: {'DaveJohnson':[70]}
after final block on first run: {'DaveJohnson':[70]}
after first block on second run: {'DaveJohnson':[70]}
after second block on second run: {'DaveJohnson':[70]}
(here you append DaveJohnson:80 to your file
after third block on second run [here you re-read DaveJohnson:70 from the file and read DaveJohnson:80] : `{'DaveJohnson':[70,70,80]
Out of curiousity, why do you have one script that is reading to a file, appending to it, reading it again and then overwriting it?
更多推荐
python空字典无法写入文本,Python写入文本文件字典显示错误信息
发布评论