python 中输出匹配字符串及其下一行

 

001、

[root@PC1 test05]# ls
a.txt  test.py
[root@PC1 test05]# cat a.txt    ## 测试数据
3333
gene
9999
kkkk
gene
7777
8888
gene
gene
0000
6666
[root@PC1 test05]# cat test.py    ## 测试程序
#!/usr/bin/env python
# -*- coding: utf-8 -*-

in_file = open("a.txt", "r")
out_file = open("result.txt", "w")

idx = 100
for i in in_file:
        i = i.strip().split()
        if i[0] == "gene":
                print("".join(i), file = out_file)
                idx = 1
        if i[0] != "gene" and idx == 1:
                print("".join(i), file = out_file)
                idx += 1
in_file.close()
out_file.close()

 

002、

[root@PC1 test05]# ls
a.txt  test.py
[root@PC1 test05]# cat a.txt
3333
gene
9999
kkkk
gene
7777
8888
gene
gene
0000
6666
[root@PC1 test05]# python3 test.py       ## 执行程序
[root@PC1 test05]# ls
a.txt  result.txt  test.py
[root@PC1 test05]# cat result.txt        ## 结果文件
gene
9999
gene
7777
gene
gene
0000

 

posted @ 2023-06-08 21:17  小鲨鱼2018  阅读(138)  评论(0编辑  收藏  举报