简体   繁体   中英

I get this error: ValueError: invalid literal for int() with base 10: '\n'

I have a part inside my code where I receive data from a text file, this is that part: last_score_file = open("/Users/lvanrem/PythonTest/last_score2", "r")

last_score_temprature = int(last_score_file.readline(1))
last_score_guess = int(last_score_file.readline(2))
add_to_random = int(last_score_file.readline(3))
last_score_file.close

it requests date from this file:

0
0
0

and it gives this error

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

let me know if you can help me...

trim endline from read value

last_score_temprature = int(last_score_file.readline(1).strip())
last_score_guess = int(last_score_file.readline(2).strip())
add_to_random = int(last_score_file.readline(3).strip())
last_score_file.close

The line you read has \n in it so the value is incorrect. The 'readline(x)' read the next x characters so your out put will be like '0, \n, 0\n' Try:

with open("/Users/lvanrem/PythonTest/last_score2", "r") as f:
   last_score_temprature = int(f.readline())
   last_score_guess = int(f.readline())
   add_to_random = int(f.readline())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM