文件编码转换工具

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安装
posted @   zyh_think  阅读(491)  评论(0编辑  收藏  举报
编辑推荐:
· DeepSeek 解答了困扰我五年的技术问题
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· 用 C# 插值字符串处理器写一个 sscanf
· Java 中堆内存和栈内存上的数据分布和特点
· 开发中对象命名的一点思考
阅读排行:
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· DeepSeek 解答了困扰我五年的技术问题。时代确实变了!
· 本地部署DeepSeek后,没有好看的交互界面怎么行!
· 趁着过年的时候手搓了一个低代码框架
· 推荐一个DeepSeek 大模型的免费 API 项目!兼容OpenAI接口!
点击右上角即可分享
微信分享提示