只读取特定行我使用for循环来读取文件,但是我只想读取特定的行,比如第26行和第30行。有什么内置的功能来实现这一点吗?谢谢
3 回答
皈依舞
TA贡献1851条经验 获得超3个赞
fp = open("file")for i, line in enumerate(fp):
if i == 25:
# 26th line
elif i == 29:
# 30th line
elif i > 29:
breakfp.close()i == n-1n
with open("file") as fp:
for i, line in enumerate(fp):
if i == 25:
# 26th line
elif i == 29:
# 30th line
elif i > 29:
break
Smart猫小萌
TA贡献1911条经验 获得超7个赞
def picklines(thefile, whatlines): return [x for i, x in enumerate(thefile) if i in whatlines]
thefilewhatlines
def yieldlines(thefile, whatlines): return (x for i, x in enumerate(thefile) if i in whatlines)
return
添加回答
举报
0/150
提交
取消
