我正在使用Python 2.7。
我想创建一个脚本来扫描文本文件中的特定关键字,例如want to test
并写入或替换字符串(b3
)。我的脚本:
#! usr/bin/python
import re
from os.path import abspath,exists
open_file = abspath("zzwrite.txt")
if exists(open_file):
with open(open_file,"r+") as write1:
for line in write1:
matching = re.match(r'.* want to test (..)',line,re.I)
if matching:
print ("Done matching")
write1.write("Success")
print >> write1,"HALELUJAH"
我的输入文本文件:
I just want to read 432
I just want to write 213
I just want to test b3 experiment
I just want to sleep for 4 hours
我设法完成了匹配,因为有一个打印的“完成匹配”,表明代码能够执行最后的“如果”条件,但是在文本文件中没有写入或替换单个字符串。每个输入文本文件中的字符串"b3"
不同,因此我不喜欢使用str.replace("b3", "xx")
方法。我在脚本中缺少什么?