-1

我有文件包含

"Starting program and 
Starting program
Loading molecule...
Initialising variables...
Starting the calculation - this could take a while!
Molecule energy = 2432.6 kcal mol-1
Calculation finished. Bye!"
import sys
import re

search_string = "Starting program"
txtlength=len(search_string)
print "txtlength",txtlength
lines = open( "C:\search.txt", "r" ).readlines()
for line in lines:
    if re.search( search_string, line ):
        print line,

    else :
        print "Not found"

我只在文件中寻找第二行,但来自此代码的输出是 1 行也显示

4

1 回答 1

0

您显示的示例不需要正则表达式:

with open("C:/search.txt") as inp:
    for line in inp:
        if line.strip() == search_string:
            print line
于 2012-10-03T10:17:38.077 回答