最近获得一个Matlab高版本的项目代码,其文本文件时utf8编码格式,而我的Matlab版本比较低,只支持gbk编码格式,于是采用Python批量转换文本编码格式。代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| import os,sys
extArray=(".m",".txt") def convert( filename, in_enc = "UTF-8", out_enc="GBK" ): try: print("convert " + filename) targetFile = open(filename,'r',encoding=in_enc) content = targetFile.read() targetFile.close()
targetFile = open(filename,'w',encoding=out_enc) targetFile.write(content) targetFile.close() except: targetFile.close() def explore(dir): for root, dirs, files in os.walk(dir): for file in files: path = os.path.join(root, file) if(path.endswith(extArray)): 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()
|
运行时采用如下命令:
1 2 3
| python -m venv env .\env\Scripts\activate python utf8_to_gbk.py filepath
|
参考链接
- Python遍历路径下文件并转换成UTF-8编码,by weixin_33826268.
- Python 批量转换文件编码格式,by huang_0430.
- GB2312、GBK、GB18030 这几种字符集的主要区别是什么?,by zhihu.
- 一图弄懂ASCII、GB2312、GBK、GB18030编码,by horstxu.
- Unicode、UTF-8、UTF-16 终于懂了,by LinuxThings.