python打印字符串所在行_Python:命中字符串时从文本文件中打印下x行

The situation is as follows:

I have a .txt file with results of several nslookups.

I want to loop tru the file and everytime it hits the string "Non-authoritative answer:" the scripts has to print the following 8 lines from that position. If it works I shoud get all the positive results in my screen :).

First I had the following code:

#!/bin/usr/python

file = open('/tmp/results_nslookup.txt', 'r')

f = file.readlines()

for positives in f:

if 'Authoritative answers can be found from:' in positives:

print positives

file.close()

But that only printed "Authoritative answers can be found from:" the times it was in the .txt.

The code what I have now:

#!/bin/usr/python

file = open('/tmp/results_nslookup.txt', 'r')

lines = file.readlines()

i = lines.index('Non-authoritative answer:\n')

for line in lines[i-0:i+9]:

print line,

file.close()

But when I run it, it prints the first result nicely to my screen but does not print the other positve results.

p.s. I am aware of socket.gethostbyname("foobar.baz") but first I want to solve this basic problem.

Thank you in advance!

解决方案

You can use the file as an iterator, then print the next 8 lines every time you find your sentence:

with open('/tmp/results_nslookup.txt', 'r') as f:

for line in f:

if line == 'Non-authoritative answer:\n':

for i in range(8):

print(next(lines).strip())

Each time you use the next() function on the file object (or loop over it in a for loop), it'll return the next line in that file, until you've read the last line.

Instead of the range(8) for loop, I'd actually use itertools.islice:

from itertools import islice

with open('/tmp/results_nslookup.txt', 'r') as f:

for line in f:

if line == 'Non-authoritative answer:\n':

print(''.join(islice(f, 8)))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值