发布时间:2019-09-03 09:27:58编辑:auto阅读(2944)
有个文本文件,需要替换里面的一个词,用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'))
上一篇: python实例-暂停一秒
下一篇: python文档之查看帮助文档方法
55020
41816
36416
31816
26723
26407
24930
20542
16476
15893
3059°
2774°
2868°
3016°
2950°
3230°
3109°
2959°
2934°
2921°