【问题标题】:What does: * ValueError: invalid literal for int() with base 10: '-' * mean?什么是:* ValueError: int() 以 10 为底的无效文字:'-' * 是什么意思?
【发布时间】:2018-04-20 06:02:43
【问题描述】:

我正在尝试编写代码来读取文件(每行包含 1 个数字)并返回文件中找到的最大 int 值(作为 int)

这是我的代码:

def max_num_in_file(filename):
"""
returns the largest integer found in  file, as an integer.
"""
infile = open(filename, "r")
lines = infile.readlines()
string_list = []
for line in lines:
    string_list.append((line[0:-1]))       
infile.close()
num_list = []
for item in string_list:
    num_list.append(int(item))
return max(num_list)

但是对于一个特定文件(其中最大 int 为 -2)我收到此错误:

Traceback (most recent call last):
  File "source.py", line 20, in <module>
    answer = max_num_in_file('max_num_in_file_test_04.txt')
  File "source.py", line 13, in max_num_in_file
num_list.append(int(item))
ValueError: invalid literal for int() with base 10: '-'

谁能帮我诊断这个错误?

【问题讨论】:

  • 你在字符串'-'上调用int,会抛出错误。
  • 你为什么不发布一个minimal reproducible example 包括item 在错误中的值?
  • 为什么要创建字符串'-'?该文件每行应该只有 1 个数字,我将 string_list 中的每个字符串转换为 num_list 中的 int
  • 显示文件内容?
  • 很遗憾,我无法访问它。

标签: python python-3.x


【解决方案1】:

您似乎只是想将破折号(或减号)转换为 int,但没有数字...

int('-2')  # No error: -2
int('-')   # Your error

您是否正在读取具有会计(或类似)格式(其中 0 被格式化为破折号)的 Excel 文件?

【讨论】:

    【解决方案2】:

    您可以通过使用try/except 块来避免这种情况,例如:

    def max_num_in_file(filename):
        """
        returns the largest integer found in  file, as an integer.
        """
        infile = open(filename, "r")
        lines = infile.readlines()
        string_list = []
        for line in lines:
            string_list.append((line))
        infile.close()
    
        num_list = []
        for item in string_list:
            try:
                num_list.append(int(item))
            except ValueError:
                print('Got ValueError for item --> ', item)
        return max(num_list)
    

    例如文件内容:

    1
    2
    3
    4
    6
    6-
    6
    -
    -
    

    max_num_in_file()的结果

    Got ValueError for item -->  6-
    Got ValueError for item -->  -
    Got ValueError for item -->  - 
    6
    

    这个try/except 块将阻止程序不停止并打印错误的内容。这样你就可以实现其他功能来清理你的数据等等......

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-09
      • 2020-01-04
      • 2010-12-22
      • 2011-07-07
      • 2019-10-14
      相关资源
      最近更新 更多