import os
import sys
import chardet
#<chardet> Python 2和3的通用编码检测器,需要安装。
#安装方法:pip install chardet==4.0.0
#获取当前工作目录路径
current_directory = os.getcwd()
print('Current Path: ' + current_directory)
os.system('pause') #按任意键继续
print('\n')
for filepath, dirnames, filenames in os.walk(current_directory):
for filename in filenames:
filename = os.path.join(filepath, filename)
fliesion = os.path.splitext(filename)[1]
#print(filename)
if fliesion == '.c' or fliesion == '.h' :
print(filename)
f = open(file = filename, mode = 'rb')
data = f.read()
dict_encode = chardet.detect(data)
if dict_encode["encoding"] == 'GB2312' :
#print(dict_encode)
f = open(filename, mode = 'r+', encoding = 'GB2312', newline = '\r\n')
str = f.read()
f.seek(0)
f.truncate()
f.close()
str.encode('utf-8')
f = open(filename, mode = 'w', encoding = 'utf-8', newline = '')
f.write(str)
f.close()
print('\n')
print('gb2312_to_utf8, Conversion completion')
input('Press <Enter> to exit...')