我正在python循环的单个迭代中创建大约200个变量(从excel文档中提取字段并将其推送到SQL数据库),并且我正在尝试找出答案。
让我们说一次迭代是我在目录中循环浏览的一个Excel工作簿。我从每个工作簿中提取大约200个字段。
如果我提取了这些字段之一(让我们说200中的字段#56)并且格式不正确(让我们说日期填写错误,即2015年9月31日,这不是真实日期)并且我执行的操作出错。
我希望循环跳过该变量,然后继续创建变量#57。我不希望循环完全转到下一个迭代或工作簿,我只希望它忽略该变量的错误,并继续进行该单循环迭代的其余变量。
我将如何做这样的事情?
在此示例代码中,即使ExpirationDate出现错误,我也想继续提取“ PolicyState”。
一些示例代码:
import datetime as dt
import os as os
import xlrd as rd
files = os.listdir(path)
for file in files: #Loop through all files in path directory
filename = os.fsdecode(file)
if filename.startswith('~'):
continue
elif filename.endswith( ('.xlsx', '.xlsm') ):
try:
book = rd.open_workbook(os.path.join(path,file))
except KeyError:
print ("Error opening file for "+ file)
continue
SoldModelInfo=book.sheet_by_name("SoldModelInfo")
AccountName=str(SoldModelInfo.cell(1,5).value)
ExpirationDate=dt.datetime.strftime(xldate_to_datetime(SoldModelInfo.cell(1,7).value),'%Y-%m-%d')
PolicyState=str(SoldModelInfo.cell(1,6).value)
print("Insert data of " + file +" was successful")
else:
continue
答案 0 :(得分:2)
使用多个try块。将可能会出错的每个解码操作包装在自己的try块中,以捕获异常,执行某些操作并继续进行下一个操作。
try:
book = rd.open_workbook(os.path.join(path,file))
except KeyError:
print ("Error opening file for "+ file)
continue
errors = []
SoldModelInfo=book.sheet_by_name("SoldModelInfo")
AccountName=str(SoldModelInfo.cell(1,5).value)
try:
ExpirationDate=dt.datetime.strftime(xldate_to_datetime(SoldModelInfo.cell(1,7).value),'%Y-%m-%d')
except WhateverError as e:
# do something, maybe set a default date?
ExpirationDate = default_date
# and/or record that it went wrong?
errors.append( [ "ExpirationDate", e ])
PolicyState=str(SoldModelInfo.cell(1,6).value)
...
# at the end
if not errors:
print("Insert data of " + file +" was successful")
else:
# things went wrong somewhere above.
# the contents of errors will let you work out what
答案 1 :(得分:1)
根据建议,您可以在每个提取变量上使用多个try
块,也可以使用自己的自定义函数为您处理try
来简化它:
from functools import reduce, partial
def try_funcs(cell, default, funcs):
try:
return reduce(lambda val, func: func(val), funcs, cell)
except Exception as e:
# do something with your Exception if necessary, like logging.
return default
# Usage:
AccountName = try_funcs(SoldModelInfo.cell(1,5).value, "some default str value", str)
ExpirationDate = try_funcs(SoldModelInfo.cell(1,7).value), "some default date", [xldate_to_datetime, partial(dt.datetime.strftime, '%Y-%m-%d')])
PolicyState = try_funcs(SoldModelInfo.cell(1,6).value, "some default str value", str)
在这里,我们使用reduce
重复多个函数,并将partial
作为带有参数的冻结函数传递。
这可以帮助您的代码看起来整洁,而不会混乱许多try
块。但是更好,更明确的方法是处理您预期可能会个别出错的字段。
答案 2 :(得分:1)
因此,基本上,您需要将xldate_to_datetime()
调用包装到try ... except
import datetime as dt
v = SoldModelInfo.cell(1,7).value
try:
d = dt.datetime.strftime(xldate_to_datetime(v), '%Y-%m-%d')
except TypeError as e:
print('Could not parse "{}": {}'.format(v, e)