python打开文件替换字符串

我想修改文件中的字符串,比如有个文件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!

上面结果是追加进去的。我只是想替换掉原来的,不想追加,应该怎么写呢?

阅读 8.5k
2 个回答
read_data = f.read()
#读写偏移位置移到首行
f.seek(0, 0)  
f.write(read_data.replace('world', 'python'))

你的写法是读取 txt 中的字符串到内存中,然后执行内存中的字符串替换,然后在追加在原来的文件中,而非替换。

file = 'hello.txt'

with open(file, 'r+') as f:
    d = f.read()
    t = d.replace('world', 'python')
    f.seek(0, 0)
    f.write(t)
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进