re.compile(),正则表达式在模式匹配前进行预编译;使用预编译代码比字符串快;
test.txt中包含以下文字:
1:li
2:test
3:num
在运行完程序,生成的target.txt中,内容为
1:li
3:num
代码清单如下:
import re
list = []
matchPattern = re.compile(r'.+:test')file = open('test.txt','r')
while 1:
line = file.readline()
if not line:
break
elif matchPattern.search(line):
pass
else:
list.append(line)
file.close()
file = open('target.txt', 'w')
for i in list:
file.write(i)
file.close()