2025年3月22日 星期六 甲辰(龙)年 月廿一 设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 编程开发 > Python

Python清空文件并替换内容

时间:08-16来源:作者:点击数:24

有个文本文件,需要替换里面的一个词,用python来完成,我是这样写的:

  • def modify_text():
  • with open('test.txt', "r+") as f:
  • read_data = f.read()
  • f.truncate() #清空文件
  • f.write(read_data.replace('apple', 'android'))

执行上面这个函数,它会把内容追加进去,而不是替换。

f.truncate()没起作用,应该怎么写才可以呢?

需要加上f.seek(0),把文件定位到position 0,没有这句的话,文件是定位到数据最后,truncate也是从这里删除,所以感觉就是没起作用。

  • def modify_text():
  • with open('test.txt', "r+") as f:
  • read_data = f.read()
  • f.seek(0)
  • f.truncate() #清空文件
  • f.write(read_data.replace('apple', 'android'))
方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门
本栏推荐