我编写了此方法以替换行中的文本。它打印正确的文本,因为我希望它被替换,但它没有更新文件中的这些更改。我对 Python 很陌生,你能帮我在哪里犯错吗?
def regFind(regx, sub_text, file_name):
c_file = io.StringIO(file_name)
for line in c_file:
match = regx.search(line)
if match:
replaced_line = re.sub(regx, sub_text, line)
line = replaced_line
#print(line)
yield line
regx = re.compile(r'^MYTEXT')
sub_text = 'NewText'
a_file = open('file.txt').read()
for line in regFind(regex, sub_text, a_file):
print(line)