python写文件时覆盖原来的实例方法

时间:2022-07-27
本文章向大家介绍python写文件时覆盖原来的实例方法,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

python写文件时覆盖原来写的方法:

使用“open(‘文件名’,’w’)”语句,以写模式打开文件,然后使用write函数写文件

最后用close函数关闭打开的文件,文件原来的内容就会被覆盖了

示例如下:

对文件操作之前的文件内容

对文件操作之后的文件内容

完整代码如下:

file=open('ss.txt','w')
file.write('123456789')
file.close()

知识点扩展:

python写文件

txt = ‘landmark.txt'
wrf = open(txt, ‘w')
wrf.write(‘test01' + ‘n')
wrf.close()

txt = ‘landmark.txt'
wrf = open(txt, ‘w')
wrf.write(‘test02' + ‘n')
wrf.close()

结果:

test02

不覆盖原来内容

txt = ‘landmark.txt'
wrf = open(txt, ‘w')
wrf.write(‘test01' + ‘n')
wrf.close()

txt = ‘landmark.txt'
wrf = open(txt, ‘a')
wrf.write(‘test02' + ‘n')
wrf.close()

结果:

test01 test02