【发布时间】:2010-12-22 22:19:49
【问题描述】:
我正在创建一个读取文件的程序,如果文件的第一行不是空白,它会读取接下来的四行。在这些行上执行计算,然后读取下一行。如果该行不为空,则继续。但是,我收到此错误:
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())
【问题讨论】:
-
你应该考虑在那里使用
with open(file_to_read, 'r') as infile:。 -
适用于目前正在查看这里的任何人。错误可能是其中一行不是整数形式。例如:“是”的格式不正确,但“3”的格式正确。对于这个问题,第一行可能没有任何 "1"s、"2"s、"3"s... 来转换为 int。
-
当输入字符串的数字之间有空格时出现此错误。此错误基本上意味着您的输入字符串对于字符串到整数的转换无效。对于转换,您的字符串应仅且仅包含以下字符:+-.0123456789
标签: python