通过python匹配和显示特定行

2024-06-25 23:11:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我在一个日志文件中有15行,我想通过python读取第4行和第10行,并在输出中显示它们,表示找到了这个字符串:

abc
def
aaa
aaa
aasd
dsfsfs
dssfsd
sdfsds
sfdsf
ssddfs
sdsf
f
dsf
s
d

请通过代码建议如何在python中实现这一点。你知道吗

为了更详细地说明这个例子,第一个字符串(字符串或行是唯一的)很容易在日志文件中找到,下一个字符串B在第一个字符串的40行之内,但是这个字符串出现在日志文件中的很多地方,所以我需要在读取字符串A之后,用前40行来读取这个字符串,并打印出与这些字符串相同的内容找到了。你知道吗

另外,我不能使用python的with命令,因为这会给我带来错误,比如“with”将成为python2.6中的保留关键字。我正在使用Python 2.5


Tags: 文件字符串代码defwithabcaaadsf
3条回答
#list of random characters
from random import randint
a = list(chr(randint(0,100)) for x in xrange(100))
#look for this
lookfor = 'b'
for element in xrange(100):
    if lookfor==a[element]:
        print a[element],'on',element
#b on 33
#b on 34

是一种简单易读的方法。你能举一个例子吗?还有其他更好的方法:)。你知道吗


作者编辑后:

最简单的方法是:

looking_for = 'findthis' i = 1 for line in open('filename.txt','r'):
    if looking_for == line:
        print i, line
    i+=1

它既高效又简单:)

def bar(start,end,search_term):
    with open("foo.txt") as fil:
        if search_term in fil.readlines()[start,end]:
            print search_term + " has found" 


>>>bar(4, 10, "dsfsfs")
"dsfsfs has found"

您可以使用:

fp = open("file")
for i, line in enumerate(fp):
    if i == 3:
        print line
    elif i == 9:
        print line
        break
fp.close()

相关问题 更多 >