我想修改文件中的字符串,比如有个文件hello.txt
,里面内容是:
hello world!
我想把world
换成python
,即完成后效果是这样:
hello python!
我这样写的代码:
file = 'hello.txt'
def demo():
with open(file, "r+") as f:
read_data = f.read()
f.write(read_data.replace('world', 'python'))
上面代码的结果是:
hello world!hello python!
上面结果是追加进去的。我只是想替换掉原来的,不想追加,应该怎么写呢?