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


333

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

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

3
您应该考虑with open(file_to_read, 'r') as infile:在那里使用。
1998年

Answers:


310

仅作记录:

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

我在这里...

>>> int(float('55063.000000'))
55063.0

必须使用!


101
我只是添加一下,以使以后的读者更加清楚,实际上,当int('1.0')抛出ValueError时,int(float('1.0'))才可以工作。
katyhuff

5
这应该是该问题的公认的最佳答案。我几乎关闭了页面,却没有看到它。谢谢!
iTurki

2
添加答案int(float('55063.000000')),因为问题是int()。比这将是真正的最高答案
Max

为什么会这样?@katyhuff
MuhamedHuseinbašić17年

7
这个答案似乎与问题无关。问题是,当您调用int()空字符串时,如何防止ValueError 。“使用float()代替”不能解决该问题。您仍然会收到ValueError。
凯文

74

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

  • 将整数的字符串表示形式传递给 int
  • 将float的字符串表示形式传递给 float
  • 将整数的字符串表示形式传递给 float
  • 将花车传递到 int
  • 将整数传递给 float

但是,你得到一个ValueError,如果你传递的字符串表示int,或任何一个字符串表示,但一个整数(包括空字符串)。如果您确实要将float的字符串表示形式传递给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

7
这个答案似乎与问题无关。问题是,当您调用int()空字符串时,如何防止ValueError 。“使用float()代替”不能解决该问题。您仍然会收到ValueError。
凯文

3
@Kevin即使这不能直接回答OP的问题。但是它确实可以帮助有这个问题并且不介意的人int(float(x))。因为这是搜索此错误时弹出的第一个问题。
Kerwin Sneijders

57

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

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

您正在尝试做的事情稍微复杂一些,但仍然不是很简单:

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

这样,它一次可以处理5条线。采用h.next()而不是next(h)Python 2.6之前的版本。

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

try:
   int('')
except ValueError:
   pass      # or whatever

4
您的try / except不能区分合理的期望值(空白/空行)和讨厌的东西(例如非整数)。
约翰·马钦

为什么要区分那些东西?
SilentGhost

3
因为一个合理地可以预期并且可以忽略,但是另一个表明存在错误
John Machin

3
为什么空白行是合理可预期的而非整数不是?
SilentGhost

1
如果您确定您的列表实际上是一个字符串化的整数列表,那么这很好。如果您不确定可以做什么n = int(line) if line.is_integer() else int(float(line))
Mike Furlender

23

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


11

原因是您将一个空字符串或一个字符串作为int的参数。检查它是否为空或包含字母字符。如果它包含字符,则只需忽略该部分。


2
这看起来更像一条评论。当您有足够的声誉时,您就可以在任何帖子中发表评论。
Joshua Drake

8

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

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


8

所以如果你有

floatInString = '5.0'

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


3

您对这一行有疑问:

while file_to_read != " ":

这找不到空字符串。它找到由一个空格组成的字符串。大概这不是您想要的。

听听其他人的建议。这不是非常惯用的python代码,如果直接遍历文件会更清楚,但是我认为这个问题也值得注意。


3

split()在一个简单的文件上测试此功能()。我遇到了同样的问题,发现那是因为split()编写不正确(异常处理)。


1
    readings = (infile.readline())
    print readings
    while readings != 0:
        global count
        readings = int(readings)

该代码有问题。readings是从文件读取的新行-它是一个字符串。因此,您不应将其与0进行比较。此外,除非您确定,否则不能将其转换为整数确实是一个。例如,空行将在此处产生错误(如您所知)。

以及为什么您需要全局计数?这无疑是Python中最糟糕的设计。


1

当您必须将以空格分隔的整数映射到列表但使用逐行输入整数时,也会发生这种情况.input()。例如,我正在HackerRank Bon- Appetit上解决此问题,并且在编译时出现以下错误 在此处输入图片说明

因此,与其逐行输入程序,不如尝试使用该map()方法将以空格分隔的整数映射到列表中。


0

我正在创建一个读取文件的程序,如果文件的第一行不是空白,它将读取接下来的四行。在这些行上执行计算,然后读取下一行。

这样的事情应该起作用:

for line in infile:
    next_lines = []
    if line.strip():
        for i in xrange(4):
            try:
                next_lines.append(infile.next())
            except StopIteration:
                break
    # Do your calculation with "4 lines" here

0

我遇到了类似的错误,结果是数据集具有python无法转换为整数的空白值。


4
您能否通过一些示例来详细说明OP如何解决该问题?
fmendez 2013年

空白值表示为空,可以将其转换为字符串float。如果您尝试转换为float,它也会显示错误
saravanan saminathan

0

尝试在同一文件对象的for循环中使用readlines()时遇到了相同的问题...我的怀疑是在同一文件对象的readline()内触发readling()导致此错误。

最好的解决方案是使用seek(0)来重置文件指针或处理条件并设置一些标志,然后通过检查设置条件为同一文件创建新对象...。


0

我最近遇到了一个案例,这些答案都不起作用。我遇到了CSV数据,其中有空字节与数据混合在一起,并且这些空字节没有被剥离。因此,我的数字字符串在剥离后由以下字节组成:

\x00\x31\x00\x0d\x00

为了解决这个问题,我做了:

countStr = fields[3].replace('\x00', '').strip()
count = int(countStr)

...其中栏位是分割线所产生的csv值清单。


0

似乎读数有时是一个空字符串,并且显然会出现错误。您可以在int(readings)命令之前在while循环中添加额外的检查,例如:

while readings != 0 | readings != '':
    global count
    readings = int(readings)

0

我很难弄清实际原因,当我们从文件中读取不正确时会发生这种情况。您需要打开文件并使用readlines()方法读取,如下所示:

with open('/content/drive/pre-processed-users1.1.tsv') as f:
    file=f.readlines()

纠正格式化的输出


0

您的答案因为此行而引发错误

readings = int(readings)
  1. 在这里,您尝试将字符串转换为非基数为10的int类型。您只能将字符串转换为以10为底的整数,否则会引发ValueError,并指出以10为底的int()的无效文字。
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.