python实现文本编码转换
下列python可以将当前目录及子目录内的 .h和.c文件的编码批量转换为utf-8 BOM
import chardet
import os
def get_encoding(file):
with open(file, "rb") as f:
data = f.read()
return chardet.detect(data)["encoding"]
for root, dirs, files in os.walk("."):
for name in files:
if os.path.splitext(name)[-1] in (".c",".h"):
file_name = os.path.join(root, name)
decoding = get_encoding(file_name)
print(file_name)
data = None
with open(file_name, "r", encoding = decoding) as f:
data = f.read()
with open(file_name, "w", encoding = "utf-8-sig") as f:
f.write(data)