循环尝试使用不同的变量

时间:2016-03-18 15:24:19

标签: python-2.7 for-loop try-catch

我从事故报告中收集公司数据 如何使用列表中的不同变量将trys和excepts循环到一个for-loop或更好的东西?

我只想简化这一点。

name = company_location
for i, j in enumerate (list):
    if j == 'Last 10 Accidents':
        last = i
        try:
            date1 = list[last+28]
            employee1 = list[last+31]
            days_lost1 = list[last+49]
            days_paid1 = list[last+43]
            with open("report.csv","a+") as report:
                report.write(str(name)+", "+str(date1)+", "+str(employee1)+", "+str(days_lost1)+", "+str(days_paid1))
            report.close()
        except (ValueError, TypeError, IndexError):
            with open("report.csv","a+") as report:
                report.write(str(name)+"\n")
            report.close()

        try:
            date2 = list[last+50]
            employee2 = list[last+53]
            days_lost2 = list[last+71]
            days_paid2 = list[last+65]
            with open("report.csv","a+") as report:
                report.write(", "+str(date2)+", "+str(employee2)+", "+str(days_lost2)+", "+str(days_paid2))
            report.close()
        except (ValueError, TypeError, IndexError):
            with open("report.csv","a+") as report:
                report.write("\n")
            report.close()

        try:
            date3 = list[last+72]
            employee3 = list[last+75]
            days_lost3 = list[last+93]
            days_paid3 = list[last+87]
            with open("report.csv","a+") as report:
                report.write(", "+str(date3)+", "+str(employee3)+", "+str(days_lost3)+", "+str(days_paid3))
        report.close()
        except (ValueError, TypeError, IndexError):
        with open("report.csv","a+") as report:
        report.write("\n")
report.close()

0 个答案:

没有答案