python空字典无法写入文本,Python写入文本文件字典显示错误信息

编程入门 行业动态 更新时间:2024-10-24 14:22:15

python空<a href=https://www.elefans.com/category/jswz/34/1770269.html style=字典无法写入文本,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写入文本文件字典显示错误信息

本文发布于:2024-02-11 20:47:52,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1683385.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字典   错误信息   文本文件   文本   python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!