ValueError:以10为基数的int()无效的字面量:“\n”

时间:2021-11-06 22:32:44

I am looking for an answer to this error with my specific code. I have searched the others and they are still so confusing.

我想用我的具体代码寻找这个错误的答案。我搜索了其他人,他们仍然很困惑。

I am unsure why this is happening.

我不确定为什么会这样。

Here is the code section that the error is referencing, followed by the error.

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

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

The error message I'm getting:

我得到的错误信息是:

    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'

Thanks everyone, I wouldn't be posting this if i didnt find a clear answer in the other posts

谢谢大家,如果我在其他帖子里没有找到一个明确的答案,我就不会发表这个帖子了。

4 个解决方案

#1


5  

This is giving you trouble:

这会给你带来麻烦:

edited: also as pointed by @PadraicCunningham, you're not calling the isdigit().. missing ()

编辑:也如@PadraicCunningham所指出的,您没有调用isdigit()..失踪()

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

You're checking only line[0] is digit and then convert the whole line to start, the line could possibly contain Tab or Space or Linefeed.

您只检查行[0]是数字,然后将整行转换为开始,该行可能包含制表符、空格或换行符。

Try this instead: start = int(line[0])

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

Also for a cleaner approach, you should strip() each line you're checking, and for the safe side in case the data being passed are like "5k" your logic needs to be a bit more SAFE, which you can use a try/except approach:

同样,对于一个更干净的方法,您应该删除()您正在检查的每一行,并且为了安全起见,如果传递的数据类似于“5k”,您的逻辑需要更安全一些,您可以使用try/除去方法:

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 ...

As a side note, you should use if/elif to avoid unnecessary if checking if previous condition has already met.

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

#2


0  

replace :

替换:

start = int(line) 

to

start = int(line.strip())   # strip will chop the '\n' 

#3


0  

Alternatively, if you want to add the number instead of the first digit, you can use .strip() to remove any whitespace and newlines.

或者,如果您想要添加数字而不是第一个数字,您可以使用.strip()来删除任何空格和换行。

if line.strip().isdigit(): 
    start = int(line.strip()) 
    score.initialScore(start) #checks if first line is a number if it is adds it to intial score

#4


0  

if the idea is to check the first line for a digit, how about using readlines instead of looping line by line; something like this.

如果想法是检查第一行的数字,如何使用readlines而不是循环线;是这样的。

I also think using regex is better

我也认为使用正则表达式更好。

import re
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    

    f = open(file,'r')
    lines_list = f.readlines()
    if bool(re.search("^-?\\d*(\\.\\d+)?$",'-112.0707922')): 
        start = int(lines_list[0]) 
        score.initialScore(start)

credit: regex borrowed from here https://*.com/a/22112198/815677

credit: regex从这里借用https://*.com/a/22112198/815677。

#1


5  

This is giving you trouble:

这会给你带来麻烦:

edited: also as pointed by @PadraicCunningham, you're not calling the isdigit().. missing ()

编辑:也如@PadraicCunningham所指出的,您没有调用isdigit()..失踪()

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

You're checking only line[0] is digit and then convert the whole line to start, the line could possibly contain Tab or Space or Linefeed.

您只检查行[0]是数字,然后将整行转换为开始,该行可能包含制表符、空格或换行符。

Try this instead: start = int(line[0])

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

Also for a cleaner approach, you should strip() each line you're checking, and for the safe side in case the data being passed are like "5k" your logic needs to be a bit more SAFE, which you can use a try/except approach:

同样,对于一个更干净的方法,您应该删除()您正在检查的每一行,并且为了安全起见,如果传递的数据类似于“5k”,您的逻辑需要更安全一些,您可以使用try/除去方法:

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 ...

As a side note, you should use if/elif to avoid unnecessary if checking if previous condition has already met.

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

#2


0  

replace :

替换:

start = int(line) 

to

start = int(line.strip())   # strip will chop the '\n' 

#3


0  

Alternatively, if you want to add the number instead of the first digit, you can use .strip() to remove any whitespace and newlines.

或者,如果您想要添加数字而不是第一个数字,您可以使用.strip()来删除任何空格和换行。

if line.strip().isdigit(): 
    start = int(line.strip()) 
    score.initialScore(start) #checks if first line is a number if it is adds it to intial score

#4


0  

if the idea is to check the first line for a digit, how about using readlines instead of looping line by line; something like this.

如果想法是检查第一行的数字,如何使用readlines而不是循环线;是这样的。

I also think using regex is better

我也认为使用正则表达式更好。

import re
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    

    f = open(file,'r')
    lines_list = f.readlines()
    if bool(re.search("^-?\\d*(\\.\\d+)?$",'-112.0707922')): 
        start = int(lines_list[0]) 
        score.initialScore(start)

credit: regex borrowed from here https://*.com/a/22112198/815677

credit: regex从这里借用https://*.com/a/22112198/815677。