数据超出预期

时间:2017-12-15 07:51:03

标签: python validation exception

我的文件包含12个月的温度设定数据:

enter image description here

我有这段代码:

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 

当我运行程序时,输出是

  

错误:数据集超出预期

1 个答案:

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