【发布时间】:2020-05-11 07:22:05
【问题描述】:
我正在使用此代码搜索一个特定的字符串:
stringToMatch = 'blah'
matchedLine = ''
#get line
with open(r'path of the text file', 'r') as file:
for line in file:
if stringToMatch in line:
matchedLine = line
break
#and write it to the file
with open(r'path of the text file ', 'w') as file:
file.write(matchedLine)
即使字符串出现多次,它也只会打印一次。我还想在出现特定单词后打印所有行。我该怎么做?
【问题讨论】:
-
您的
break说一旦找到一个案例就离开for loop。您可能需要删除/修改它。
标签: python python-3.x text