python之文件修改的两种方式

c.txt的内容
alex is sb
sb is alex
egon is hahahahh

方式一:文本编辑器采用的方式
优点:省硬盘空间

with open('c.txt',modse='rt',encoding='utf-8') as f:
	res = f.read()
	data = res.replace('alex','dsb')
	print(date)
with open ('c.txt',mode='wt',encoding= 'utf-8') as f1:
	f1.write(data)

方式二:
优点:省内存空间

import os

with opne('c.txt',mode='rt',encoding='utf-8') as f,\
	    open('.c.txt.swap',mode='wt',encoding='utf-8') as f1:
	    for line in f:
	    	f1.write(line.replace('alex','dsb')
os.remove('c.txt')
os.remove('.c.txt.swap','c.txt')
	

猜你喜欢

转载自blog.csdn.net/weixin_47237915/article/details/114685177