Skip to main content
 首页 » 编程设计

python之使用 python next() 和 strip() 检索以下行

2025年05月04日15webabcd

我在使用 next() 和 strip() 检索我正在阅读的行之后的行时遇到问题。测试数据看起来像这样:

@abcde:111/2 
ABCDEFGHIj 
+abcde:111/2 
bla11 
@abcde:115/2 
JDIJSKNDIJ 
+abcde:115/2 
bla13 
@abcde:113/2 
djijwkoken 
+abcde:113/2 
bla15 

我的目标是删除所有以“@”开头且第二行包含“N”的 4 行。预期的测试输出应如下所示:

@abcde:111/2 
ABCDEFGHIj 
+abcde:111/2 
bla11 
@abcde:113/2 
djijwkoken 
+abcde:113/2 
bla15 

这是我的代码 (delete_N.py),我在远程 Ubuntu 服务器上使用 Mac OS 终端运行它,使用 python 2.7:

import sys 
 
filename1 = sys.argv[1] #file to process 
 
data = open(filename1, 'r') 
 
def del_N(input1): 
    for line in input1: 
        if line[:1] == '@' and 'N' not in next(input1).strip(): 
            print line.strip() 
            for i in range(3): 
                print next(input1).strip() 
 
del_N(data) 

但是我得到以下错误:

Traceback (most recent call last): 
  File "delete_N.py", line 14, in <module> 
    del_N(data) 
  File "delete_N.py", line 12, in del_N 
    print next(input1).strip() 
StopIteration 

我做错了什么?

请您参考如下方法:

在您的程序中,您正在从文件中读取数据。检查Lego's answer ,他非常清楚地解释了错误。

你可以这样做。该程序假定文件中的行数是 4 的倍数。

with open("Input.txt", "r") as input_file: 
    for line1 in input_file: 
        line2, line3, line4 = [next(input_file) for _ in xrange(3)] 
        if "N" not in line2: 
            print line1 + line2 + line3 + line4.rstrip() 

输出

@abcde:111/2 
ABCDEFGHIj 
+abcde:111/2 
bla11 
@abcde:113/2 
djijwkoken 
+abcde:113/2 
bla15