0

我正在创建一个测验,其中每个用户的分数都保存到一个外部文本文件中。但是,每当我输出数学简单测验中最高分的报告时,它都会显示:ValueError: invalid literal for int() with base 10: ''

这似乎是问题所在: if highestScore <= int(line.strip()):

        with open("mathsEasy.txt") as mathsEasyFile:
        highestScore = 0
        for line in mathsEasyFile:
            if highestScore <= int(line.strip()):
                highestScore = int(line.strip())
    mathsEasyFile.close()

    print "The highest score is", highestScore

基本上,每次用户进行数学简单测验时,它都会将他们的分数保存到名为mathsEasy.txt 文本文件的文本文件中:the username : score例如,Kat15 : 4我只需要输出最高分,而不是用户名。

4

2 回答 2

1

现在您已经添加了文件如何工作的示例:

with open("mathsEasy.txt") as mathsEasyFile:
    highestScore = max(int(line.split(' : ')[1]) for line in mathsEasyFile if len(line.strip() != 0)
print("The highest score is %d" % highestScore)

分解以帮助您更好地理解它:

highestScore = 0 # in my previous code, I use max() instead
with open("mathsEasy.txt") as mathsEasyFile: # open the file
    for line in mathsEasyFile: # for each line in the file,
        if len(line.strip()) == 0: # if the current line is empty,
            continue # ignore it and keep going to the next line
        _,score = line.split(' : ') # split the line into its components
        if int(score) > highestScore: # if this score is better,
            highestScore = int(score) # replace the best score
print("The highest score is %d" % highestScore)
于 2018-01-29T02:10:44.410 回答
0

一些东西...

  • 它可能只是在 StackOverflow 中进行格式化,但请确保您的缩进是正确的;在mathsEasyFile:您可能想要除最后的打印语句缩进之外的所有内容之后。
  • 我认为您会想要添加类似的lines = mathsEasyFile.readlines()内容并使用类似的内容进行迭代for line in lines:。我不相信您当前的设置没有读取任何文件内容。不正确。请参阅下面的评论。
  • mathsEasyFile.close()已经通过使用with语句为您完成

澄清编辑

# something like this ought to work
with open("mathsEasy.txt") as mathsEasyFile:
    highestScore = 0
    for line in mathsEasyFile:
        if highestScore <= int(line.strip()):
            highestScore = int(line.strip())

print "The highest score is", highestScore
于 2018-01-29T01:47:52.723 回答