1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
| 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()
|