1. 程式人生 > >Python_批量修改檔案的編碼格式

Python_批量修改檔案的編碼格式

使用說明:

1、使用工具:Python2.7.6+chardet2.3.0,chardet2.3.0下載地址:點選這裡

2、環境配置:Python安裝+配置環境變數,chardet解壓放在Python安裝目錄\Lib\site-packages下

舉例:批量修改當前路徑下所有.cpp檔案的編碼格式為UTF-8,程式碼如下:

import os
import sys
import codecs
import chardet

def convert(filename,out_enc="UTF-8"):
	try:
		content=codecs.open(filename,'r').read()
		source_encoding=chardet.detect(content)['encoding']
		print source_encoding

		content=content.decode(source_encoding).encode(out_enc)
		codecs.open(filename,'w').write(content)
	except IOError as err:
		print("I/O error:{0}".format(err))

def explore(dir):
	for root,dirs,files in os.walk(dir):
		for file in files:
			if os.path.splitext(file)[1]=='.cpp':
				print file
				path=os.path.join(root,file)
				convert(path)

def main():
	explore(os.getcwd())

if __name__=="__main__":
	main()

歡迎指正,本人QQ:164845244