“列表索引超出范围"当尝试使用python从文本文件输出行时 [英] "list index out of range" when try to output lines from a text file using python

查看:148
本文介绍了“列表索引超出范围"当尝试使用python从文本文件输出行时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从文本文件中提取偶数行并将其输出到新文件.但是用我的代码,python警告我列表索引超出范围".有人可以帮助我吗?谢谢〜

I was trying to extract even lines from a text file and output to a new file. But with my codes python warns me "list index out of range". Anyone can help me? THANKS~

代码:

f = open('input.txt', 'r')
i = 0
j = 0 
num_lines = sum(1 for line in f)
newline = [0] * num_lines
print (num_lines)
for i in range(1, num_lines):
    if i % 2 == 0:
        newline[i] = f.readlines()[i]
            print i, newline[i]
    i = i + 1
f.close()
f = open('output.txt', 'w')
for j in range(0,num_lines):
    if j % 2 == 0:
        f.write(newline[j] + '\n')
    j = j + 1
f.close()

输出:

17
Traceback (most recent call last):
  File "./5", line 10, in <module>
    a = f.readlines()[1]
IndexError: list index out of range

推荐答案

您还可以使用itertools.islice方法:

from itertools import islice

with open('input') as fin, open('output', 'w') as fout:
    fout.writelines(islice(fin, None, None, 2))

这将节省模数运算并将行写入置于系统级别.

This saves the modulus operation and puts the line writing to system level.

这篇关于“列表索引超出范围"当尝试使用python从文本文件输出行时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆