从文件中读取并生成

2024-04-24 18:45:21 发布

您现在位置: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

我怎样才能解决这个问题


Tags: 代码infromfordatadeflineopen
1条回答
网友
1楼 · 发布于 2024-04-24 18:45:21

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

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

相关问题 更多 >