import os
import sys
import chardet
#<chardet> Python 2和3的通用编码检测器,需要安装。
#安装方法:pip install chardet==4.0.0
#print os.path.abspath('.') #获取当前工作目录路径
#print os.path.abspath('..') #获取当前工作的父目录 !注意是父目录路径
#获取当前工作目录路径
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(filename, 'rb')
data = f.read()
dict_encode = chardet.detect(data)
if dict_encode["encoding"] == 'utf-8' :
#print(dict_encode)
f = open(filename, mode = 'r+', encoding = 'utf-8', newline = '\r\n')
str = f.read()
f.seek(0)
f.truncate()
f.close()
str.encode('GB2312')
f = open(filename, mode = 'w', encoding = 'GB2312', newline = '')
f.write(str)
f.close()
print('\n')
print('utf8_to_gb2312, Conversion completion')
input('Press <Enter> to exit...')