[英]How can I fix this: ValueError invalid literal for int() with base 10: ''? Python
import os
txt_file = 'highscore.txt'
score = total_points
if not os.path.exists(txt_file):
with open(txt_file, 'w') as f:
f.write('Score: {score}\n'
+ 'Name: {name}')
with open(txt_file, 'r') as f:
previous_score = int(f.readline().split()[-1])
# compare the previous score with current score and write the highest score
if previous_score < score:
with open(txt_file, 'w') as f:
f.write(f'Score: {score}\n'
+ f'Name: {name}')
I understand that because I have Score:
on the line, it isn't coming back as just the score.我明白这一点,因为我有
Score:
在线上,它不仅仅是得分。 If I use re.findall
I can get just the score but it turns into a list, and I still can't use int(previous_score) < int(score)
.如果我使用
re.findall
我只能得到分数,但它会变成一个列表,我仍然不能使用int(previous_score) < int(score)
。 How do I go about making this work?我该如何做这个工作?
Thank you to the previous commenter, Sachin, who helped me get this far by the way.感谢之前的评论者 Sachin,顺便说一句,他帮助我走到了这一步。
edit: I managed to get it with all of your help.编辑:在您的帮助下,我设法得到了它。 Thank you so much!
太感谢了!
what's wrong with previous_score = int(f.readline().split()[-1])
previous_score = int(f.readline().split()[-1])
有什么问题
In your code you are literally writing "Score: {score}" in the txt_file
.在您的代码中,您实际上是在
txt_file
中写入“Score: {score}”。 You don't substitute {score}
with the value of the variable score
.您不要用变量
score
的值替换{score}
。 You can open that file in an editor and confirm.您可以在编辑器中打开该文件并确认。 To do this substitution, add
f
before each string, ie: your code should begin要进行此替换,请在每个字符串之前添加
f
,即:您的代码应该开始
with open(txt_file, 'w') as f:
f.write(f'Score: {score}\n'
+ f'Name: {name}')
Then, to extract the score from previous_score
, carefull it is the whole line, you should split the line into words and keep the last element, then convert it to integer: int(previous_score.split()[-1])
.然后,要从
previous_score
中提取分数,注意它是整行,您应该将行拆分为单词并保留最后一个元素,然后将其转换为 integer: int(previous_score.split()[-1])
。
It sounds like you want to extract an int from a string.听起来您想从字符串中提取一个 int 。 For example,
例如,
previous_score = 'Score: 150\n' #Which you read from the file with .readline()
score = previous_score.split()[-1] #Splits a string into words. Take last item.
print(int(score))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.