Skip to content

Instantly share code, notes, and snippets.

Last active Nov 12, 2022
What would you like to do?
将文件夹下的.c、.h、.asm文件转换为utf-8格式。使用方法:python [path]
#for /d %i in (*.*) do (python %i)
import os
import sys
import codecs
import chardet
import sys
def convert(file, in_enc="GBK", out_enc="UTF-8"):
:param file: 文件路径
:param in_enc: 输入文件格式
:param out_enc: 输出文件格式
in_enc = in_enc.upper()
out_enc = out_enc.upper()
print("convert [ " + file.split('\\')[-1] + " ].....From " + in_enc + " --> " + out_enc )
f =, 'r', in_enc)
new_content =, 'w', out_enc).write(new_content)
# print (
except IOError as err:
print("I/O error: {0}".format(err))
def list_folders_files(path):
返回 "文件夹" 和 "文件" 名字
:param path: "文件夹"和"文件"所在的路径
:return: (list_folders, list_files)
:list_folders: 文件夹
:list_files: 文件
list_folders = []
list_files = []
for file in os.listdir(path):
file_path = os.path.join(path, file)
if os.path.isdir(file_path):
return (list_folders, list_files)
if __name__ == "__main__":
path = sys.argv[1]
(list_folders, list_files) = list_folders_files(path)
print("Path: " + path)
for fileName in list_files:
filePath = path + '\\' + fileName
if '.c' in fileName or '.h' in fileName or '.asm' in fileName:
with open(filePath, "rb") as f:
data =
codeType = chardet.detect(data)['encoding']
convert(filePath, codeType, 'UTF-8')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment