Skip to main content
 首页 » 编程设计

python之值错误 : invalid literal for int() with base 10: '\n'

2025年05月04日15EasonJim

我正在使用我的特定代码寻找此错误的答案。我搜索了其他人,他们仍然很困惑。

我不确定为什么会这样。

这是错误引用的代码部分,后面是错误。

def processScores( file, score): 
#opens file using with method, reads each line with a for loop. If content in line 
#agrees with parameters in  if statements, executes code in if statment. Otherwise, ignores line     
 
    with open(file,'r') as f: 
        for line in f:  #starts for loop for all if statements 
            if line[0].isdigit:  
                start = int(line)  
                score.initialScore(start) #checks if first line is a number if it is adds it to intial score 

我收到的错误消息:

    Traceback (most recent call last): 
  File "<pyshell#20>", line 1, in <module> 
    processScores('theText.txt',score) 
  File "C:/Users/christopher/Desktop/hw2.py", line 49, in processScores 
    start = int(line) 
ValueError: invalid literal for int() with base 10: '\n' 

谢谢大家,如果我在其他帖子中没有找到明确的答案,我就不会发布这个

请您参考如下方法:

这给你带来了麻烦:

已编辑:正如@PadraicCunningham 所指出的,您没有调用 isdigit().. missing ()

if line[0].isdigit():  
    start = int(line) 

你只检查 line[0] 是数字,然后将整行转换为 start,line 可能包含 Tab或空格或换行。

试试这个:start = int(line[0])

另外,为了更简洁的方法,您应该strip() 您正在检查的每一行,并且为了安全起见,以防传递的数据类似于"5k" 您的逻辑需要更加安全,您可以使用try/except 方法:

for line in f: 
    line = line.strip() 
    # edited: add `if line and ...` to skip empty string 
    if line and line[0].isdigit(): 
        try: 
            start = int(line)  
            score.initialScore(start) 
        except ValueError: 
            # do something with invalid input 
    elif #... continue your code ... 

作为旁注,您应该使用 if/elif 来避免不必要的 if 检查先前的条件是否已经满足。