python add utf-8 character set
3390 ワード
python 3.*従来のバージョンでは、漢字などのアジア文字を印刷するには、pyファイルの先頭に符号化情報を追加します.ここではutf-8符号化を追加するツールの方法を簡単に書いて、自分で使いやすいようにしました.実はpyDevIDEでは、ファイルごとに先頭を定義できます.私のブログにはあります.ここでは、指定するディレクトリ内のすべてを巡回することができる.pyのファイルは、符号化を追加していないので、すべて符号化を追加します.
#-*-coding:utf-8-*-
'''
Created on 2012-4-22
@author: kanpiaoxue
'''
from string import strip
import os
class PythonUtil(object):
UTF8_STRING = '#-*-coding:utf-8-*-'
def __init__(self):
pass
def addAddUtf8(self, inputFile):
needUtf8ListFiles = self.needUtf8(inputFile)
count = len(needUtf8ListFiles)
if count > 0:
for tmpFile in needUtf8ListFiles:
print tmpFile, ' need to add ', self.UTF8_STRING
readFile = None
writeFile = None
try:
readFile = open(tmpFile, 'r')
lines = readFile.readlines()
lines.insert(0, self.UTF8_STRING + '
')
writeFile = open(tmpFile, 'w')
writeFile.writelines(lines)
print 'add ', self.UTF8_STRING, ' to ', tmpFile
finally:
if readFile is not None:
readFile.close()
if writeFile is not None:
writeFile.flush()
writeFile.close()
print '
-------------- result report begin --------------'
if count > 0:
print 'add ', self.UTF8_STRING, ' to ', count, ' files successfully.'
else:
print 'there are not any files needing to add ', self.UTF8_STRING
print '-------------- result report end --------------
'
def needUtf8(self, inputFile):
needUtf8ListFiles = []
if not os.path.isdir(inputFile):
print '[', inputFile, '] is not a valid folder. Please check it.'
return needUtf8ListFiles
for root, dirs, files in os.walk(inputFile):
for name in files:
f = os.path.join(root, name)
if f.endswith('.py') :
tmpFile = None
try:
tmpFile = open(f, 'r')
lines = tmpFile.readlines()
if len(lines) > 0:
if strip(lines[0]) != self.UTF8_STRING:
needUtf8ListFiles.append(f)
else:
needUtf8ListFiles.append(f)
finally:
if tmpFile is not None:
tmpFile.close()
return needUtf8ListFiles
if __name__ == '__main__':
f = r'E:\workspace_python'
pythonUtil = PythonUtil()
pythonUtil.addAddUtf8(f)