从文件读取并生成生成器的函数

时间:2018-04-27 18:44:31

标签: python

在以下代码中:

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

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

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

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处理程序中的一行,以便在坏行中止或跳过它。