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
我怎样才能解决这个问题?
解决方案
为了使您的代码更明确地说明其意图并简化调试,我会稍微更改您的代码:
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
处理程序中的一行以在错误的行上中止或跳过它。
推荐阅读
- javascript - 我怎样才能单击特定按钮但不是所有按钮
- java - 让视图的加载方法接受模型实例是否违反 MVP?
- r - 拟合矩阵元素 - 伽玛分布
- android - 如何使用 EffectFactory.EFFECT_TINT 在 Android 中设置颜色强度
- android - 在 webstrom 或 VS 代码终端中运行本机项目时,模拟器不会自动启动
- java - 如何限制用户回答?
- javascript - 无法让 Chrome 扩展程序通过 XML 请求运行其 PHP 文件
- docker - Docker 运行上传失败 - 上传失败,因为找不到 zip_path
- java - 应用程序中的本机代码(C++ 库)是否可以访问 Android 文件系统?
- firebase - Firestore 中的两个对象相互引用