我的文件包含12个月的温度设定数据:
我有这段代码:
if n <= 0: #validate the size
raise ValueError("Invalid data set size value.")
for i in range(n):
line = infile.readline() #read a data set
if line != "":
raise RuntimeError("more data sets than expected") #check if there is more lines than expected
当我运行程序时,输出是
错误:数据集超出预期
答案 0 :(得分:0)
您有12行数据,您可以逐行读取12次。在第12次读取后,line
包含最后一行数据,并且不会被清除。这就是line != ""
求值为true的原因,并抛出错误。也许你应该再读一次
for i in range(n):
line = infile.readline() #read a data set
if infile.readline() != "":
raise RuntimeError("more data sets than expected") #check if there is more lines than expected
请注意,有更好的方法可以解决这个问题:
lines = infile.readlines()
if len(lines) > n:
raise RuntimeError("more data sets than expected") #check if there is more lines than expected