如何在python中从文本文件的特定行打印
我正在使用以下代码搜索特定字符串:如何在python中从文本文件的特定行打印,python,python-3.x,text,Python,Python 3.x,Text,我正在使用以下代码搜索特定字符串: 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 w
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)
即使字符串出现多次,也只打印一次。我还想在特定单词出现后打印所有行。如何做到这一点?设置一个标记以跟踪您何时看到该行,并将该行写入同一循环中的输出文件
string_to_match = "blah"
should_print = False
with open("path of the text file", "r") as in_file, open("path of another text file", "w") as out_file:
for line in in_file:
if string_to_match in line:
# Found a match, start printing from here on out
should_print = True
if should_print:
out_file.write(line)
设置一个标记以跟踪何时看到该行,并在同一循环中将这些行写入输出文件
string_to_match = "blah"
should_print = False
with open("path of the text file", "r") as in_file, open("path of another text file", "w") as out_file:
for line in in_file:
if string_to_match in line:
# Found a match, start printing from here on out
should_print = True
if should_print:
out_file.write(line)
您可以这样修改代码:-
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 + '\n'
#and write it to the file
with open(r'path of the text file ', 'w') as file:
file.write(matchedLine)
希望你收到了 您可以这样修改代码:-
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 + '\n'
#and write it to the file
with open(r'path of the text file ', 'w') as file:
file.write(matchedLine)
希望你收到了 您的中断表示,一旦发现一个案例,就保留for循环。您可能需要删除/修改它。您的中断表示在找到一个案例后保留for循环。您可能需要删除/修改它。