发布时间:2019-09-03 09:27:58编辑:auto阅读(2496)
有个文本文件,需要替换里面的一个词,用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文档之查看帮助文档方法
52350
52263
42399
39290
33766
30721
29460
24386
24256
22628
125°
135°
143°
148°
137°
251°
238°
254°
252°
298°