只用python打印文本文件中第一个找到的字符串

时间:2014-12-03 10:08:46

标签: python

有没有办法只在找到字符串时打印第一个字符串?例如:

文本文件:

date....
author:...
this is a list:
there a string 1 here
and there a string 2 there
but also have string 3 here
don't have string 4 there

代码:

for line in open(os.path.join(dirname, filename), "r").readlines():
    if line.find('string') != -1:
        print "found ", line

印刷:

found there a string 1 here

3 个答案:

答案 0 :(得分:1)

您可以使用break停止循环。并in检查子字符串。

for line in open(os.path.join(dirname, filename), "r").readlines():
    if 'string' in line:
        print("found "+line)
        break

答案 1 :(得分:0)

使用with的替代方式:

with open(os.path.join(dirname, filename),'r') as f:
    for line in f:
        if 'string' in line: 
            print("found ", line)
            break 

答案 2 :(得分:0)

对代码的修改很少:

for line in open(os.path.join(dirname, filename), "r").readlines():
    if line.find('string') >=0:
        print "found ", line
        break                       # to stop loop when string is found

find返回找到的字符串的位置,然后返回-1