ValueError:基数为10的int()的无效文字:''

Sar*_*Cox 252 python

我正在创建一个读取文件的程序,如果文件的第一行不是空白,则会读取接下来的四行.在这些行上执行计算,然后读取下一行.如果该行不为空,则继续.但是,我收到此错误:

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

它正在读取第一行但不能将其转换为整数.

我该怎么做才能解决这个问题?

代码:

file_to_read = raw_input("Enter file name of tests (empty string to end program):")
try:
    infile = open(file_to_read, 'r')
    while file_to_read != " ":
        file_to_write = raw_input("Enter output file name (.csv will be appended to it):")
        file_to_write = file_to_write + ".csv"
        outfile = open(file_to_write, "w")
        readings = (infile.readline())
        print readings
        while readings != 0:
            global count
            readings = int(readings)
            minimum = (infile.readline())
            maximum = (infile.readline())
Run Code Online (Sandbox Code Playgroud)

小智 261

仅供记录:

>>> int('55063.000000')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '55063.000000'
Run Code Online (Sandbox Code Playgroud)

我来这里......

>>> float('55063.000000')
55063.0
Run Code Online (Sandbox Code Playgroud)

必须使用!

  • 为了给未来的读者提供更多的清晰度,我只是添加,当int('1.0')抛出ValueError时,int(float('1.0'))确实有效. (85认同)
  • 当我根据上面的答案将字符串转换为浮点数时,它显示“ValueError:无法将字符串转换为浮点数:” (9认同)
  • 这应该是这个问题的公认答案.我几乎关闭了页面而没有看到它.谢谢! (5认同)
  • 这个答案似乎与问题没有任何关系.问题是当你在一个空字符串上调用`int()`时,询问如何阻止ValueError."使用float()代替"并不能解决这个问题.你仍然得到一个ValueError. (4认同)
  • 为什么会出现这种情况?@凯蒂赫夫 (3认同)
  • 添加回答int(float('55063.000000')),因为问题是get int().而不是它将真正的顶级答案 (2认同)

Sil*_*ost 53

Pythonic迭代文件并转换为int的方法:

for line in open(fname):
   if line.strip():           # line contains eol character(s)
       n = int(line)          # assuming single integer on each line
Run Code Online (Sandbox Code Playgroud)

你要做的事情稍微复杂一些,但仍然不是直截了当的:

h = open(fname)
for line in h:
    if line.strip():
        [int(next(h).strip()) for _ in range(4)]     # list of integers
Run Code Online (Sandbox Code Playgroud)

这样它当时处理5行.使用h.next()而不是next(h)Python 2.6之前.

你的原因ValueError是因为int无法将空字符串转换为整数.在这种情况下,您需要在转换之前检查字符串的内容,或者除了错误之外:

try:
   int('')
except ValueError:
   pass      # or whatever
Run Code Online (Sandbox Code Playgroud)

  • 你的try/except不区分合理可预期的东西(空白/空行)和非整数的讨厌的东西. (4认同)
  • 因为一个是合理的可预期和可忽略的,但另一个是错误的指示 (3认同)
  • 为什么一个合理可预期的空行和非整数不是? (3认同)

Pet*_*ter 50

以下内容在python中完全可以接受:

  • 将整数的字符串表示形式传递给 int
  • 将float的字符串表示形式传递给 float
  • 将整数的字符串表示形式传递给 float
  • 将一个浮球传递进去 int
  • 将整数传入 float

但是,你得到一个ValueError,如果你传递的字符串表示int,或任何一个字符串表示,但一个整数(包括空字符串).如果你确实想要将float的字符串表示传递给a int,正如@katyhuff指出的那样,你可以先转换为float,然后转换为整数:

>>> int('5')
5
>>> float('5.0')
5.0
>>> float('5')
5.0
>>> int(5.0)
5
>>> float(5)
5.0
>>> int('5.0')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '5.0'
>>> int(float('5.0'))
5
Run Code Online (Sandbox Code Playgroud)

  • @Kevin尽管这并没有直接回答OP的问题。然而,它确实可以帮助那些有这个问题并且不介意“int(float(x))”的人。因为这是搜索此错误时弹出的第一个问题。 (6认同)
  • 哇,这太愚蠢了。为什么不让 int() 接受字符串?这正是我所期望的,而不是先将其类型转换为浮点...... (5认同)
  • 这个答案似乎与问题没有任何关系.问题是当你在一个空字符串上调用`int()`时,询问如何阻止ValueError."使用float()代替"并不能解决这个问题.你仍然得到一个ValueError. (4认同)

raj*_*mar 11

原因是你得到一个空字符串或字符串作为参数进入int检查之前它是空的还是包含字母字符,如果它包含而不是简单地忽略该部分.

  • 这正是我所需要的,谢谢。我不明白为什么这个论坛上的人如此痴迷于对这个网站进行微观管理 (4认同)
  • 这看起来更像是一条评论。当您有足够的声誉时,您将能够对任何帖子发表评论。 (2认同)

Bra*_*123 11

我找到了解决方法。Python会将数字转换为浮点数。只需先调用float,然后将其转换为int即可: output = int(float(input))

  • 这个答案不等于@FdoBad给出的答案吗? (4认同)

Har*_*vey 9

所以如果你有

floatInString = '5.0'
Run Code Online (Sandbox Code Playgroud)

你可以将其转换为intfloatInInt = int(float(floatInString))


Joi*_*ish 7

出现此错误的原因是您试图将空格字符转换为整数,这是完全不可能且受限制的,这就是为什么会出现此错误。在此处输入图片说明

检查您的代码并更正它,它将正常工作