有没有办法只在找到字符串时打印第一个字符串?例如:
文本文件:
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
答案 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