通過python實現對文件轉碼,其實處理很簡單:
1.打開讀取文件內容到一個字符串變量中,把gbk編碼文件,對字符串進行decode轉換成unicode
2.然后使用encode轉換成utf-8格式。
3.最后把字符串重新寫入到文件中即可。
在對文件進行轉碼之前,需要先對文件的編碼格式進行校驗,如果已經是utf-8格式的文件,不做decode轉碼處理,否則會報錯。
因此這里使用chardet包進行返回文件的編碼格式。
使用 pip install chardet 安裝即可引入使用。
腳本如下:
convergbk2utf.py
# -*- coding:utf-8 -*-
__author__ = 'tsbc'
import os,sys
import chardet
def convert( filename, in_enc = "GBK", out_enc="UTF8" ):
try:
print "convert " + filename,
content = open(filename).read()
result = chardet.detect(content)#通過chardet.detect獲取當前文件的編碼格式串,返回類型為字典類型
coding = result.get('encoding')#獲取encoding的值[編碼格式]
if coding != 'utf-8':#文件格式如果不是utf-8的時候,才進行轉碼
print coding + "to utf-8!",
new_content = content.decode(in_enc).encode(out_enc)
open(filename, 'w').write(new_content)
print " done"
else:
print coding
except IOError,e:
# except:
print " error"
def explore(dir):
for root, dirs, files in os.walk(dir):
for file in files:
path = os.path.join(root, file)
convert(path)
def main():
for path in sys.argv[1:]:
if os.path.isfile(path):
convert(path)
elif os.path.isdir(path):
explore(path)
if __name__ == "__main__":
main()
執行
python
convergbk2utf.py d:\test
可以講d:\test目錄中的所有文件,轉碼成utf8.
PS:想要做的容錯性更高一下的話,可以對要轉碼的文件類型再加個判斷進行過濾,對filename通過分析,只轉換你想要轉換的文件類型即可。
