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

标签 python lines next strip

我在使用 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

关于python - 使用 python next() 和 strip() 检索以下行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21128364/

相关文章:

python - 未找到 OpenCV2 Python createBackgroundSubtractor 模块

sed - 如何使用 sed 取消注释第二个模式匹配上的多行?

html - 如何使用 CSS 中默认背景颜色之外的另一种背景颜色绘制线条?

postgresql - 将记录与postgresql中的先前记录进行比较

python - 使用搜索和调用 next() 读取文件时有没有办法返回?

python - 我的代码应该有一个(非常糟糕的)AI 将他的井字棋 O 放在棋盘上的随机位置

python - 在包含元组的列表列表中查找重复项

python - Pandas 数据框中的数字与字符串数据的散点图

java - 在数组中拆分 .txt 文件

javascript - 具有多个链接的 Accordion