简体   繁体   English

ValueError:int()以10为底的无效文字:'\\ n'

[英]ValueError: invalid literal for int() with base 10: '\n'

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 谢谢大家,如果我在其他帖子中找不到明确的答案,我就不会发布此帖子

This is giving you trouble: 这给您带来麻烦:

edited: also as pointed by @PadraicCunningham, you're not calling the isdigit().. missing () 编辑:也正如@PadraicCunningham所指出的那样,您没有调用isdigit().. missing()

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. 您只检查line[0]是数字,然后将整行转换为start ,该line可能包含Tab或Space或Linefeed。

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: 同样,为了更简洁的方法,您应该对要检查的每一行都进行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 ...

As a side note, you should use if/elif to avoid unnecessary if checking if previous condition has already met. 附带说明, if检查先前条件是否已满足,则应使用if/elif来避免不必要的操作。

replace : 替换:

start = int(line) 

to

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

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

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. 这样的事情。

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://stackoverflow.com/a/22112198/815677 信用:从这里借来的正则表达式https://stackoverflow.com/a/22112198/815677

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 ValueError:int()以10为底的无效文字:b&#39;1 \\ n5 \\ n&#39; - ValueError: invalid literal for int() with base 10: b'1\n5\n' 我收到此错误: ValueError: invalid literal for int() with base 10: '\n' - I get this error: ValueError: invalid literal for int() with base 10: '\n' ValueError:以10为底的int()的无效文字:&#39;2 \\ n3&#39; - ValueError: invalid literal for int() with base 10: '2\n3' 显示 ValueError: 以 10 为基数的 int() 的无效文字:&#39;\\n&#39; - Showing ValueError: invalid literal for int() with base 10: '\n' ValueError: 基数为 10 的 int() 的文字无效:&#39;40 1 3 4 20\\n&#39; - ValueError: invalid literal for int() with base 10: '40 1 3 4 20\n' ValueError: int() 以 10 为底的无效文字:'81?36N' - ValueError: invalid literal for int() with base 10 : '81?36N' ValueError:以 10 为底的 int() 的无效文字:'20.00\n' - ValueError: invalid literal for int() with base 10: '20.00\n' ValueError:int() 的无效文字,基数为 10:&#39;59574966\\n9&#39; - ValueError: invalid literal for int() with base 10: '59574966\n9' ValueError:int() 的无效文字,基数为 10:&#39;26.02.2018&#39; - ValueError: invalid literal for int() with base 10: '26.02.2018' 第8行:ValueError:int()以10为底的无效文字:“&#39; - Line 8: ValueError: invalid literal for int() with base 10: ' '
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM