标签:文件 内容 文件中 strong utf-8 and pen with line
文件的修改操作:文件并没有修改操作,实际是将一个编写的新文件覆盖了原有的文件
替换文件中的某个内容:
with open(‘old.txt‘,‘r‘,encoding=‘utf-8‘) as read_f,\
open(‘.old.txt.swap‘,swap,‘w‘,encoding=‘utf-8‘) as write_f:
msg=read_f.read()
msg=msg.replace(‘alex‘,‘SB‘)
print(msg)
wirte_f.write(msg)
os.remove(‘old.txt‘) #删除原有的文件
os.rename(‘.old.txt.swap‘,‘old.txt‘) #将交换文件替换为原有的文件
然后再替换回来:
with open(‘old.txt‘,‘r‘,encoding=‘utf-8‘) as read_f,\
open(‘.old.txt.swap‘,swap,‘w‘,encoding=‘utf-8‘) as write_f:
for line in read_f:
if ‘SB‘ in line:
line=line.replace(‘SB‘,‘alex‘)
write_f.write(line)
os.remove(‘old.txt‘) #删除原有的文件
os.rename(‘.old.txt.swap‘,‘old.txt‘) #将交换文件替换为原有的文件
标签:文件 内容 文件中 strong utf-8 and pen with line
原文地址:http://www.cnblogs.com/sexiaoshuai/p/7204466.html