发布时间:2019-09-03 09:27:58编辑:auto阅读(2087)
有个文本文件,需要替换里面的一个词,用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文档之查看帮助文档方法
48866
47934
38709
35858
30285
27039
26072
20904
20700
19067
502°
596°
604°
611°
587°
572°
637°
711°
830°
928°