a.txt是一个包含以下字符串的文件:
g g abc
abc
457625
er
oldstring = "abc"
newstring = "def"
with open('a.txt', 'r') as f:
data = f.read()
re.sub(r"b{}b".format(oldstring), r"b{}b".format(newstring), data)
with open('b.txt', 'w') as out:
out.write(data)
有了这个python代码,我想我最终可以拥有b.txt,在那里我可以拥有"abc";转向";def";。令人惊讶的是,我在.txt.中得到了完全相同的字符串
有人能告诉我代码中的错误在哪里吗?
您需要将re.sub
的输出分配回原始变量。
data = re.sub(r"b{}b".format(oldstring), newstring, data)