做什么:* ValueError:对于带有基数10的int()的无效文字:' - ' *是什么意思?

时间:2018-04-20 06:02:43

标签: python python-3.x

我正在尝试编写读取文件的代码(每行包含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)

然而,对于一个特定文件(其中max 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: '-'

任何人都可以为我诊断此错误吗?

2 个答案:

答案 0 :(得分:0)

您似乎只是尝试将字符串(或减号)转换为int,但没有数字......

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

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

答案 1 :(得分:0)

您可以使用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)

e.g。文件内容:

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块会阻止程序停止并打印出错的内容。这样您就可以实现其他功能来清理数据等......

相关问题