# coding utf-8
import os
import chardet
def find_all_file(path: str) -> str:
for root, dirs, files in os.walk(path):
for f in files:
if f.endswith('.h'):
fullname = os.path.join(root, f)
yield fullname
pass
pass
pass
def judge_coding(path: str) -> dict:
with open(path, 'rb') as f:
c = chardet.detect(f.read())
if c['encoding'] != 'UTF-8-SIG': # 排除的编码格式
return c
# 修改文件编码方式
def change_to_utf_file(path: str):
for i in find_all_file(path):
c = judge_coding(i)
if c:
try:
change(i, c['encoding'])
print("[成功] {} 编码方式已从 {} 编码更改成功".format(i, c['encoding']))
except:
print("[失败] {} 编码方式从 {} 编码更改失败".format(i, c['encoding']))
def change(path: str, coding: str):
with open(path, 'r', encoding=coding) as f:
text = f.read()
with open(path, 'w', encoding='utf-8-sig') as f:
f.write(text)
# 查看所有文件编码方式
def check(path: str):
for i in find_all_file(path):
with open(i, 'rb') as f:
print(chardet.detect(f.read())['encoding'], ': ', i)
def main():
change_to_utf_file('你的路径')
if __name__ == '__main__':
main()
Comments