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

2024-05-08 20:06:37 发布

您现在位置: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())

Tags: 文件tonamereadinputreadlinerawopen
3条回答

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

  • 将整数的字符串表示形式传递到int
  • 将浮点的字符串表示形式传递到float
  • 将整数的字符串表示形式传递到float
  • 将浮点值传递到int
  • 将整数传递到float

但是,如果将float的字符串表示形式传递到int中,或者传递除整数(包括空字符串)以外的任何字符串表示形式,则会得到ValueError。如果您确实要将浮点的字符串表示形式传递给int,正如@katyhuff在上面指出的,您可以先转换为浮点,然后再转换为整数:

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

在文件上迭代并转换为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行。在Python 2.6之前使用h.next(),而不是next(h)

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

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

仅作记录:

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

我来了。。。

>>> float('55063.000000')
55063.0

必须使用!

相关问题 更多 >