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

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

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

尤及   2021-01-29 我要评论

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

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

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

示例如下:

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

企业微信截图_20200619150413.jpg

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

企业微信截图_20200619150530.jpg

完整代码如下:

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

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们