如何跳过Python中单循环迭代的一部分

问题描述 投票:0回答:3

我在python循环的单个迭代中创建了大约200个变量(从excel文档中提取字段并将它们推送到SQL数据库)并且我正在尝试解决问题。

假设单个迭代是我在目录中循环的单个Excel工作簿。我从每个工作簿中提取大约200个字段。

如果我提取这些字段中的一个(让我们说字段#56中的200)并且格式不正确(假设日期填写错误即2015年9月31日这不是真正的日期)并且它出错我正在执行的操作。

我希望循环跳过该变量并继续创建变量#57。我不希望循环完全转到下一个迭代或工作簿,我只是希望它忽略该变量上的错误并继续该单循环迭代的其余变量。

我该怎么做这样的事情?

在此示例代码中,我想继续提取“PolicyState”,即使ExpirationDate有错误。

一些示例代码:

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               
python continue try-except
3个回答
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
投票

使用多个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
投票

所以,基本上你需要将你的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)
© www.soinside.com 2019 - 2024. All rights reserved.