![](/img/trans.png)
[英]ValueError: invalid literal for int() with base 10: b'1\n5\n'
[英]ValueError: invalid literal for int() with base 10: '\n'
我正在尋找使用我的特定代碼對此錯誤的答案。 我搜索了其他人,但他們仍然如此困惑。
我不確定為什么會這樣。
這是錯誤所引用的代碼部分,后跟錯誤。
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或Space或Linefeed。
請嘗試以下方法: 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
檢查先前條件是否已滿足,則應使用if/elif
來避免不必要的操作。
替換:
start = int(line)
至
start = int(line.strip()) # strip will chop the '\n'
或者,如果要添加數字而不是第一位數字,則可以使用.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
如果想法是檢查第一行是否有數字,那么如何使用讀取行而不是逐行循環? 這樣的事情。
我也認為使用正則表達式會更好
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)
信用:從這里借來的正則表達式https://stackoverflow.com/a/22112198/815677
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.