class BadData(ValueError):
pass
class CSVReader():
def __init__(self, path):
self.path = path
def row_to_record(row):
try:
row == 0
except BadData:
print("Found an empty row")
fileList = []
fileList = fileList + row
return fileList
def load():
with open('laliga.csv', mode='r'):
csvfilereader = csv.reader(csvfile)
for row in csvfilereader:
row_to_record(row)
obj1 = CSVReader('laliga.csv')
obj1.load()
该程序的目标是首先加载csv文件,然后将此文件中的每一行发送到row_to_record方法。在这里,我验证并查看是否有任何行为空。如果它们是空的,那么我会引发一个名为Bad Data的自定义异常类。
Laliga.csv文件包含以下行:
No Team MP W D L F A D P最后5场比赛
1皇家马德里29 22 5 2 78 30 48 71 WWWWW
2 Barcelona 30 21 6 3 88 26 62 69 WWWLW
3马德里竞技30 18 7 5 55 23 32 61 WWWWW
4塞维利亚30 17 7 6 52 37 15 58 LDLDD
5 Villarreal 30 14 9 7 42 23 19 51 WLLWW
修改:添加指向文件的链接.. https://docs.google.com/spreadsheets/d/11XCesWFl-gvm7j0SU2CJQZ2QVEiDK4-iKj3FKFC0LDo/edit?usp=sharing
答案 0 :(得分:0)
class BadData(Exception):
pass
class CSVReader(object):
def __init__(self, path):
self.path = path
def row_to_record(row):
fileList = []
fileList = fileList + row
return fileList
def load():
with open('laliga.csv', mode='r'):
csvfilereader = csv.reader(csvfile)
for row in csvfilereader:
if not row:
raise BadData('Row not found!')
row_to_record(row)
obj1 = CSVReader('laliga.csv')
try:
obj1.load()
except BadData:
print "Found an empty row!"
你很亲密!你想要做的是在你注意到它后立即提出异常。这发生在" load"当你遇到空行时。
请注意,我做了一些更改: