【问题标题】:Finding the Hishest Score. ValueError: invalid literal for int() with base 10: ''寻找最高分。 ValueError: int() 以 10 为底的无效文字:''
【发布时间】:2018-01-29 01:37:16
【问题描述】:

我正在创建一个测验,其中每个用户的分数都保存到一个外部文本文件中。但是,每当我输出数学简单测验中最高分的报告时,它都会显示: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 我只需要输出最高分,而不是用户名。

【问题讨论】:

  • 你的缩进关闭了吗?然而,这个错误表明line.strip() 是空字符串(''),所以当它试图将其解析为整数时,Python 会抛出一个错误。您的文件中可能有空行
  • 不,我检查了我的文件,里面有信息
  • 我并不是暗示整个文件是空的,但是如果任何一行是空的,你的代码就会抛出那个错误。我建议在尝试将其解析为整数之前检查该行是否为空,例如if len(line.strip()) != 0:。或者,您可以简单地将其添加到现有的 if 语句中,例如if len(line.strip()) != 0 and highestScore &lt;= int(line.strip()):
  • 好的。解析是什么意思?

标签: python python-2.7 int text-files highest


【解决方案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)

【讨论】:

  • 我现在明白了。谢谢
【解决方案2】:

一些事情......

  • 它可能只是在 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

【讨论】:

  • "我想你会想要添加类似 lines = matsEasyFile.readlines() 的东西,并像 for line in lines 一样遍历它:你当前的设置没有读取任何文件内容,我不相信。”这是不正确的。 for line in filestream: 是有效的 Python 语法。问题是空行
  • 我对文件流的看法是正确的。谢谢指正。
  • 原代码中的错误是由于试图用int()解析一个空行,这段代码仍然会抛出同样的错误。您应该添加一个检查以确保该行不为空,例如if len(line.strip()) != 0 and highestScore &lt;= int(line.strip()):
  • 有道理
猜你喜欢
  • 2018-09-09
  • 2020-01-04
  • 2010-12-22
  • 2011-07-07
  • 2019-10-14
  • 2022-05-19
相关资源
最近更新 更多