一. 文件修改
f = open("yesterday.txt",'r')
f1 = open("yesterday2.txt",'w')
for line in f:
if "会不会比较睡得着," in line:
line = line.replace("会不会比较睡得着,","shagouzi") #replace行替换,注意顺序
f1.write(line)
f.close()
f1.close()
with语句
为了避免打开文件后忘记关闭,可以通过with管理上下文:
with open("yesterday.txt",'r') as f: #格式: # 有冒号,下行缩进
print(f.read())
with open("yesterday.txt",'r') as f1,open("yesterday2.txt",'r') as f2: #可以同时打开多个文件
print(f1.read())
print(20*'-')
print(f2.read())
二. 字符编码与转码
import sys
print(sys.getdefaultencoding()) #打印系统默认编码
s = "哈喽"
s_gbk = s.encode("gbk")
print(s_gbk)
print(s.encode())
gbk_to_utf8 = s_gbk.decode("gbk").encode("utf-8")
print("utf8",gbk_to_utf8)
大家参考大牛的博客吧:http://www.cnblogs.com/luotianshuai/articles/5735051.html