win7下,python3.4读写中文文件比python2方便一点儿了。只要在打开文件时指定编码格式就可以了。
即:
f = open(fname,‘r‘,encoding=‘utf-8‘)
f2 = open(fname2,‘w‘,encoding=‘utf-8‘)
下面是一个调试通过的例子。读log2目录下utf-8格式的日志文件,搜索“失败”字符串,把搜到的结果写到utf-8格式的rst.txt文件中。
# -*- coding: utf-8 -*-
import os
import sys
def main(filedir,keystr):
filelists = os.listdir(filedir)
fname2 = ‘g:/log/rst.txt‘
fw = open(fname2,‘w‘,encoding=‘utf-8‘)
for fnamestr in filelists:
fname = os.path.join(filedir,fnamestr)
print(fname,keystr)
#continue
fhandle = open(fname,‘r‘,encoding=‘utf-8‘)
line2 = fhandle.readline()
while line2:
if line2.find(keystr)>=0:
print(" ==",line2)
fw.write(line2)
line2 = fhandle.readline()
fhandle.close()
fw.close()
if __name__ == ‘__main__‘:
filedir = "g:/log2"
keystr = "失败"
main(filedir,keystr)
print("Done!")本文出自 “happy366” 博客,请务必保留此出处http://happy366.blog.51cto.com/2203682/1750563
原文:http://happy366.blog.51cto.com/2203682/1750563