python写文件时覆盖原来的代码方法实例
本篇文章小编给大家分享一下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
PHP之友评论