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())
247
3
以Pythonic方式遍历一个文件并转换为int。
你想做的事情稍微复杂一些,但仍然不简单。
这样一来,它就能一次处理5行。在Python 2.6之前使用
h.next()
而不是next(h)
。你出现
ValueError
的原因是int
不能将空字符串转换为整数。在这种情况下,你需要在转换前检查字符串的内容,或者除了一个错误。这段代码有一个问题。
readings
是从文件中读出的新行--它是一个字符串。此外,你不能把它转换为一个整数,除非你确信它确实是一个整数。例如,空行在这里会产生错误(你肯定已经发现了)。你为什么需要全局计数?这无疑是Python中糟糕的设计。
像这样的事情应该是可行的。