2014-12-03 161 views
0

有没有办法打印第一个字符串,只有当它发现字符串?例如:只打印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 
+2

你能解释更多的?它不清楚,第一个字符串? – Hackaholic 2014-12-03 10:10:54

回答

1

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

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

替代方式使用with

with open(os.path.join(dirname, filename),'r') as f: 
    for line in f: 
     if 'string' in line: 
      print("found ", line) 
      break 
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

相关问题