#!/usr/bin/env python
# -*- coding:utf-8 -*-
#第二行声明编码 gbk
#文件修改
f1=open('xxx.txt','r',encoding='utf-8')
f2=open('x2.txt','w',encoding='utf-8')
print(f1.readline())
for line in f1:
if 'nihao' in line:
line = line.replace('hao','hAo')
f2.write(line)
f1.close()
f2.close()
#自动关闭文件
with open('x2.txt','r',encoding='utf-8') as f:
for i in f:
print(i)
#打开多个文件
with open('xxx.txt') as f1,open('x2.txt') as f2:
pass
#一行代码不超过80个字符
with open('xxx.txt') as f1,open('x2.txt') as f2 ,\
open('qq.txt','r',encoding='utf-8') as f3:
pass
#显示系统默认编码
import sys
print(sys.getdefaultencoding())
#转码
a='你好' #默认utf-8
b=a.encode("gbk") #转换成GBK 不显示中文
print(b)
c=b.decode("gbk").encode("utf-8") #转utf8
print(c)