【问题标题】:I get this error: ValueError: invalid literal for int() with base 10: '\n'我收到此错误: ValueError: invalid literal for int() with base 10: '\n'
【发布时间】:2020-08-02 18:20:15
【问题描述】:

我的代码中有一部分用于从文本文件接收数据,这就是那部分: 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

它从这个文件中请求日期:

0
0
0

它给出了这个错误

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

如果你能帮助我,请告诉我...

【问题讨论】:

    标签: python file valueerror


    【解决方案1】:

    从读取值修剪端线

    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
    

    【讨论】:

    • 请不要在 SO 中复制答案
    • 它解决了这个错误,但我添加了这个:ValueError: invalid literal for int() with base 10: ''
    【解决方案2】:

    您阅读的行中有\n,因此该值不正确。 'readline(x)' 读取接下来的 x 个字符,因此您的输出将类似于 '0, \n, 0\n' 试试:

    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())
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-01
      • 1970-01-01
      • 2021-12-25
      • 2019-04-16
      • 1970-01-01
      • 1970-01-01
      • 2022-08-01
      • 2011-02-06
      相关资源
      最近更新 更多