我该如何解决这个问题:ValueError invalid literal for int() with base 10: ''? Python

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}')

我知道因为我有 Score: 在线,所以它不会只返回分数。如果我使用 re.findall 我只能得到分数但它变成了一个列表,我仍然不能使用 int(previous_score) < int(score)。我该如何着手完成这项工作?

感谢之前的评论者 Sachin,是他帮助我走到这一步。

编辑: 在你的帮助下,我设法得到了它。非常感谢!

怎么了 previous_score = int(f.readline().split()[-1])

听起来您想从字符串中提取一个整数。例如,

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))

在您的代码中,您实际上是在 txt_file 中编写 "Score: {score}"。您不要将 {score} 替换为变量 score 的值。您可以在编辑器中打开该文件并确认。要进行此替换,请在每个字符串前添加 f,即:您的代码应以

开头
with open(txt_file, 'w') as f:
    f.write(f'Score: {score}\n'
        + f'Name: {name}')

然后,要从previous_score中提取分数,注意它是整行,你应该将这行拆分成单词并保留最后一个元素,然后将其转换为整数:int(previous_score.split()[-1])