首页 > 解决方案 > 从文件中读取并生成生成器的函数

问题描述

在以下代码中:

def data_from_file(fname, sep=';'):

    file_iter = open(fname, 'r')
    for line in file_iter:
        line = line.strip()
        if 0 == len(line): continue
        row = line.split(sep)
        try:
            leg = int(row[2])
        except ValueError:
            leg = "NONE"
        yield DATA(type=row[1], leg=leg, time=int(row[3]), id=row[0])

我收到错误消息:

in data_from_file
    leg = int(row[2])
IndexError: list index out of range

我怎样才能解决这个问题?

标签: python

解决方案


为了使您的代码更明确地说明其意图并简化调试,我会稍微更改您的代码:

def data_from_file(fname, sep=";"):
    with open(fname) as file_iter:
        for line in file_iter:
            line = line.strip()
            if not line:
                continue
            try:
                id, type_, leg, time = line.split(sep)
            except ValueError:
                # raise ValueErr("Bad line: %s" % (line,))
                # print("Bad line, skipping: %s" % (line, )
            try:
                leg = int(leg):
            except ValueError:
                leg = "NONE"
            yield DATA(type_, leg, int(time), id)

取消注释第一个ValueError处理程序中的一行以在错误的行上中止或跳过它。


推荐阅读