使用Python替换文本中的内容

要想替换文件的内容,首先你要读取文件,将该文件内容存储的内存中,再来判断你要替换的内容是否在读出的文本中,如果在,就替换,整体替换好将其写入文件。当我们写入的时候,会将文件中的旧内容删除掉,再写入新的内容。

具体python代码实现如下:

old="我的"
new="萤火虫"
with open(path,'r+',encoding='utf-8') as filetxt:
    lines=filetxt.readlines()
    filetxt.seek(0)
    for line in lines:
        if old in line:
            lines="".join(lines).replace(old,new)
    filetxt.write("".join(lines))

或者是

old="萤火虫"
new="燕子"
with open(path,'r+',encoding='utf-8') as filetxt:
    lines=filetxt.read()
    filetxt.seek(0)
  
    lines=lines.replace(old,new)
    filetxt.write(lines)

两个代码的区别在于下面的代码是整体读取文本内容,并且lines为str类型,所以可以对其整体使用replace进行替换,上面的代码是按行读取,并且其lines是list,所以需要将其转化为str,并且使用循环进行替换。