我正在使用以下代码。如何添加错误检查。 如果有任何错误,请替换继续阅读 例如:如果音量为N \ a或缺失,请替换为“值”。 不要跳过线,不要停止。
reader = csv.reader(idata.split("\r\n"))
stocks = []
for line in reader:
if line == '':
continue
stock, price, volume, stime = line
price = float(price)
volume = int(volume)
stocks.append((stock, price, volume, stime))
答案 0 :(得分:2)
执行以下操作:
def isRecordValid(stock,price,volume,stime):
#do input validation here, return True if record is fine, False if not. Optionally raise an Error here and catch it in your loop
return True
reader = csv.reader(idata.split("\r\n"))
stocks = []
for line in reader:
if line == '':
continue
stock, price, volume, stime = line
try:
if isRecordValid(stock,price,volume,stime):
price = float(price)
volume = int(volume)
stocks.append((stock, price, volume, stime))
except Exception as e:
print "either print or log and error here, using 'except' means you can continue execution without the exception terminating your current stack frame and being thrown further up"
基本上定义另一种方法(或内联)以验证库存,价格,数量和价格是否符合您的预期。我试图在这里捕获任何错误,以防你的float()或int()调用将价格和音量字符串转换为它们的预期类型因任何原因而失败。