预期处理结果:
出现异常后的结果:
对比后可以发现:该异常出现之后,后面的语句不再解释进行。
异常产生原因:迭代器next读到了尾部(这里是文件尾),无数据可读。
异常解决方案:
try: #Python next()迭代器完成会引发StopIteration异常
prestr1 = next(reader) #此行做你本来的期望做的迭代操作
except StopIteration:
break #这里填写你希望怎样处理这个异常,因为我是while(1)读文件,所以break。
#如果你希望结束程序,请import sys后,sys.exit()
用于测试的源码和文件:
import csv
import string
import sys
with open("C:\\Users\\76485\\Desktop\\testcsv1.csv","r") as csvfile:
#open(filename,mode) 打开一个文件 r只读 w写入 a追加
Ans = [0]*24
for i in range(24):
Ans[i] = 0
reader = csv.reader(csvfile)
header_row = next(reader)
#cz = 0
while(1):#未能处理好读入到文件尾
#cz += 1
#if cz == 10 :
# break 可行
try: #Python next()迭代器完成会引发StopIteration异常
prestr1 = next(reader)
except StopIteration:
break
#if prestr1[0] == "":
# break 无效
#if not prestr1:
# break 无效
#if(len(prestr1) <= 5):
# break
str1 = prestr1[0]
print(str1)
lens = len(str1)
flag = 0
#str(str1)
for i in range(lens):
if str1[i] == ':':
flag = i
break
x = str1[flag - 1]
x = int(x)
#print(x)
#x -= 48
if str1[flag - 2] >= '0' and str1[flag - 2] <= '9':
y = str1[flag - 2]
y = int(y)
x += 10 * y
x = int(x)
print(x)
Ans[x] += 1
for i in range(24):
print(Ans[i],end = ',')
time,lineID,stationID,deviceID,status,userID,payType
2019/1/7 0:00,B,15,785,0,Dd8e03b983df853eb2bff5b38834beb8e,3
2019/1/7 0:00,B,5,222,1,De2cd8aad3d8c9315f42f55fe330b0cd1,3
2019/1/7 0:00,B,5,223,1,D045a19c9d41f734ee6ab1995666bf066,3
2019/1/7 0:01,C,34,1644,0,Bf9a5d3f0e2eaa5bd08f521f20258cce6,1
2019/1/7 0:01,C,59,2783,0,D3b81b3d1400d7afadad36bf235cbb406,3
2019/1/7 0:01,C,34,1643,0,B1117ddc7ada9383fa0e206dd8779e2df,1
2019/1/7 0:01,B,10,541,0,Dea7be7c1371600e427317ba3fcc42086,3
2019/1/7 0:01,C,34,1629,0,B2e579fa0480062d568546967f624aaab,1
2019/1/7 0:01,B,10,541,0,D61f5937bd306e6f1f24ad38703250585,3
2019/1/7 0:01,C,34,1628,0,B8c460a03977c959e441662bef0bce774,1
2019/1/7 0:01,C,64,2996,0,B1c2b23a8c2e172cabadb309772802230,1
2019/1/19 13:53,B,12,625,0,Afab0bc19b201b65bbbf799c5c46b0476,0
2019/1/19 13:53,C,59,2782,0,A36943885d8ca26c127fb0381860fcdd1,0
2019/1/19 13:53,A,74,3386,0,Aa40c16e0aaccf56ad26ae437ffaaf8f2,0
2019/1/19 13:53,B,12,622,0,Ae297f6df6a91b90dca6b3214cc558aea,0
2019/1/19 13:53,C,50,2430,0,D1f89a63968a14fe1ca9cc748bd5d67bb,3
2019/1/19 13:53,C,66,3063,0,Ca97731f481db4f1ab19bc1908331d1c7,2
2019/1/19 13:53,B,20,1055,1,C0c0158edc8d3e2f25d51b9a577d50937,2
2019/1/19 13:53,A,69,3200,1,Ce9376fb6c8fca3eb1e34006eb0536247,2
2019/1/19 13:53,A,75,3407,0,C9b6d31aa753fae22c58c8b2b3abe3192,2
2019/1/19 13:53,C,57,2706,1,C7e049627c85c72d712815cc62dd7f0cb,2
2019/1/19 13:53,C,50,2412,0,C2eab562d0404a9b0eac2d8c8b2e7f95f,2