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

我正在创建一个程序,读取一个文件,如果文件的第一行不是空的,它就读取接下来的四行。 对这些行进行计算,然后再读下一行。 如果该行不是空的,就继续。 然而,我得到了这个错误。

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

以Pythonic方式遍历一个文件并转换为int。

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
评论(5)
    readings = (infile.readline())
    print readings
    while readings != 0:
        global count
        readings = int(readings)

这段代码有一个问题。readings是从文件中读出的新行--它是一个字符串。此外,你不能把它转换为一个整数,除非你确信它确实是一个整数。例如,空行在这里会产生错误(你肯定已经发现了)。

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

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