问题:ValueError:以10为底的int()的无效文字:”

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

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

I am creating a program that reads a file and if the first line of the file is not blank, it reads the next four lines. Calculations are performed on those lines and then the next line is read. If that line is not empty it continues. However, I am getting this error:

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

It is reading the first line but can’t convert it to an integer.

What can I do to fix this problem?

The code:

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

回答 0

仅作记录:

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

必须使用!

Just for the record:

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

Got me here…

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

Has to be used!


回答 1

以下内容在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

The following are totally acceptable in python:

  • passing a string representation of an integer into int
  • passing a string representation of a float into float
  • passing a string representation of an integer into float
  • passing a float into int
  • passing an integer into float

But you get a ValueError if you pass a string representation of a float into int, or a string representation of anything but an integer (including empty string). If you do want to pass a string representation of a float to an int, as @katyhuff points out above, you can convert to a float first, then to an integer:

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

回答 2

迭代文件并转换为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

Pythonic way of iterating over a file and converting to int:

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

What you’re trying to do is slightly more complicated, but still not straight-forward:

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

This way it processes 5 lines at the time. Use h.next() instead of next(h) prior to Python 2.6.

The reason you had ValueError is because int cannot convert an empty string to the integer. In this case you’d need to either check the content of the string before conversion, or except an error:

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

回答 3

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

I found a work around. Python will convert the number to a float. Simply calling float first then converting that to an int will work: output = int(float(input))


回答 4

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

The reason is that you are getting an empty string or a string as an argument into int. Check if it is empty or it contains alpha characters. If it contains characters, then simply ignore that part.


回答 5

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

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

The reason you are getting this error is that you are trying to convert a space character to an integer, which is totally impossible and restricted.And that’s why you are getting this error.enter image description here

Check your code and correct it, it will work fine


回答 6

所以如果你有

floatInString = '5.0'

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

So if you have

floatInString = '5.0'

You can convert it to int with floatInInt = int(float(floatInString))


回答 7

您对这一行有疑问:

while file_to_read != " ":

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

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

You’ve got a problem with this line:

while file_to_read != " ":

This does not find an empty string. It finds a string consisting of one space. Presumably this is not what you are looking for.

Listen to everyone else’s advice. This is not very idiomatic python code, and would be much clearer if you iterate over the file directly, but I think this problem is worth noting as well.


回答 8

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

Please test this function (split()) on a simple file. I was facing the same issue and found that it was because split() was not written properly (exception handling).


回答 9

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

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

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

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

There’s a problem with that code. readings is a new line read from the file – it’s a string. Therefore you should not compare it to 0. Further, you can’t just convert it to an integer unless you’re sure it’s indeed one. For example, empty lines will produce errors here (as you’ve surely found out).

And why do you need the global count? That’s most certainly bad design in Python.


回答 10

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

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

This could also happen when you have to map space separated integers to a list but you enter the integers line by line using the .input(). Like for example I was solving this problem on HackerRank Bon-Appetit, and the got the following error while compiling enter image description here

So instead of giving input to the program line by line try to map the space separated integers into a list using the map() method.


回答 11

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

这样的事情应该起作用:

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

I am creating a program that reads a file and if the first line of the file is not blank, it reads the next four lines. Calculations are performed on those lines and then the next line is read.

Something like this should work:

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

回答 12

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

I was getting similar errors, turns out that the dataset had blank values which python could not convert to integer.


回答 13

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

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

I got into the same issue when trying to use readlines() inside for loop for same file object… My suspicion is firing readling() inside readline() for same file object caused this error.

Best solution can be use seek(0) to reset file pointer or Handle condition with setting some flag then create new object for same file by checking set condition….


回答 14

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

\x00\x31\x00\x0d\x00

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

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

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

I recently came across a case where none of these answers worked. I encountered CSV data where there were null bytes mixed in with the data, and those null bytes did not get stripped. So, my numeric string, after stripping, consisted of bytes like this:

\x00\x31\x00\x0d\x00

To counter this, I did:

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

…where fields is a list of csv values resulting from splitting the line.


回答 15

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

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

This seems like readings is sometimes an empty string and obviously an error crops up. You can add an extra check to your while loop before the int(readings) command like:

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

回答 16

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

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

纠正格式化的输出

I had hard time figuring out the actual reason, it happens when we dont read properly from file. you need to open file and read with readlines() method as below:

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

It corrects the formatted output


回答 17

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

readings = int(readings)
  1. 在这里,您尝试将字符串转换为非基数为10的int类型。您只能将字符串转换为以10为底的整数,否则会引发ValueError,并指出以10为底的int()的无效文字。

your answer is throwing errors because of this line

readings = int(readings)
  1. Here you are trying to convert a string into int type which is not base-10. you can convert a string into int only if it is base-10 otherwise it will throw ValueError, stating invalid literal for int() with base 10.

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。