搜索文件 [英] Searching a file

查看:28
本文介绍了搜索文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是参考我昨天发布的问题在3中搜索文件不同的方式

This is in reference to a question I posted yesterday Searching a file in 3 different ways

我现在只需要两件事就可以了,搜索文件,然后打印一条找到搜索结果的行,然后将所有行打印到文件末尾.

I just require help now on two things, searching a file and and printing the line a search result is found on and all the lines after it to the end of the file.

最后,我需要编码方面的帮助,例如,我搜索文件并打印找到搜索结果的行以及搜索结果前后的许多行.用户定义搜索结果之前和之后打印的行数,并且前后的行数相同.

Lastly i need help on coding were i search a file and print the line a search result is found on and a number of lines before and after the the search result. The number of lines printed before and after the search result is defined by the user and is the before/after amount of lines are the same.

推荐答案

第一部分

for line in open("file"):
    line=line.rstrip()
    if "search" in line:
        f=1
    if f: print line

第二部分

context=3
search="myword"
f=open("file")
d={}
for n,line in enumerate(f):
    d[n%context]=line.rstrip()
    if search in line:
        for i in range(n+1,n+1+context):
            print d[i%context]
        for i in range(1,context):
            print f.next().rstrip()
f.close()

这篇关于搜索文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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