在Python脚本中使用正则表达式
我正在尝试编写python脚本来搜索和替换此行: 剩余时间3总计 用空行 这是我的剧本:在Python脚本中使用正则表达式,python,regex,search,replace,Python,Regex,Search,Replace,我正在尝试编写python脚本来搜索和替换此行: 剩余时间3总计 用空行 这是我的剧本: import glob read_files = glob.glob("*.agr") with open("out.txt", "w") as outfile: for f in read_files: with open(f, "r") as infile: outfil
import glob
read_files = glob.glob("*.agr")
with open("out.txt", "w") as outfile:
for f in read_files:
with open(f, "r") as infile:
outfile.write(infile.read())
with open("out.txt", "r") as file:
filedata = file.read()
filedata = filedata.replace(r'#time\s+residue\s+[0-9]\s+Total', 'x')
with open("out.txt", "w") as file:
file.write(filedata)
使用这个,我无法得到任何更换。为什么会这样?代码的其余部分工作正常。输出文件没有更改,因此我怀疑找不到图案
谢谢。str.replace方法替换固定的子字符串。如果要替换正则表达式模式的匹配项,请使用
re.sub
:
import re
filedata = re.sub(r'#time\s+residue\s+[0-9]\s+Total', 'x', filedata)
str.replace
方法替换固定的子字符串。如果要替换正则表达式模式的匹配项,请使用re.sub
:
import re
filedata = re.sub(r'#time\s+residue\s+[0-9]\s+Total', 'x', filedata)
非常感谢。这成功了!非常感谢。这成功了!