• 文件编码转换工具


    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安装
  • 相关阅读:
    字符串:序列自动机
    图论学习——最大团与最大独立集
    点分治
    图论:Johnson全源最短路
    停止更新博客
    将Eclipse中现有的java类生成类图
    problem:SVN error: (501 Not Implemented)
    SVN 修改URL路径
    eclipse中,把java函数代码折叠/展开
    Build类
  • 原文地址:https://www.cnblogs.com/zjzyh/p/4885097.html
Copyright © 2020-2023  润新知