文件编码转换工具

1.起因:工作需要

源码是utf-8编码的文件, 加载到vs中后无法编译,需要转换成gbk(gb2312)编码格式的文件

2.实现:使用python简单的实现了文件夹内遍历修改文件编码格式

  • 以下是源码
import chardet
import os

def strJudgeCode(str):
	return chardet.detect(str)

def readFile(path):
	try:
		f = open(path, 'r')
		filecontent = f.read()
	finally:
		if f:
			f.close()

	return filecontent

def WriteFile(str, path):
	try:
		f = open(path, 'w')
		f.write(str)
	finally:
		if f:
			f.close()

def converCode(path):
	file_con = readFile(path)
	result = strJudgeCode(file_con)
	#print(file_con)
	if result['encoding'] == 'utf-8':
		#os.remove(path)
		a_unicode = file_con.decode('utf-8')
		gb2312 = a_unicode.encode('gbk')	
		WriteFile(gb2312, path)

def listDirFile(dir):
	list = os.listdir(dir)
	for line in list:
		filepath = os.path.join(dir, line)
		if os.path.isdir(filepath):
			listDirFile(filepath)
		else:
			print(line)
			converCode(filepath)			

if __name__ == '__main__':
	listDirFile(u'G:Classess')
  • 注:chardet是python的一个第三方库,可以用pip install chardet安装
原文地址:https://www.cnblogs.com/zjzyh/p/4885097.html