obsidian/笔记文件/2.笔记/代码文件转UTF8格式.md
2025-03-26 00:02:56 +08:00

1.1 KiB

#python

import os
import chardet

def detect_encoding(file_path):
    with open(file_path, 'rb') as file:
        raw_data = file.read()
    result = chardet.detect(raw_data)
    return result['encoding'], raw_data

def convert_to_utf8_without_bom(file_path):
    encoding, raw_data = detect_encoding(file_path)
    # Check if the file is UTF-8 with BOM
    if encoding == 'utf-8-sig':
        # Write the file back without BOM
        with open(file_path, 'w', encoding='utf-8') as file:
            file.write(raw_data.decode('utf-8-sig'))
        print(f"Converted {file_path} from UTF-8 with BOM to UTF-8 without BOM")
    else:
        print(f"{file_path} is not UTF-8 with BOM, no conversion needed")

def traverse_folder_and_convert_cs_files(folder_path):
    for root, dirs, files in os.walk(folder_path):
        for file in files:
            if file.endswith('.cs'):
                cs_file_path = os.path.join(root, file)
                convert_to_utf8_without_bom(cs_file_path)

# Specify the path to the folder you want to traverse
folder_path = 'C:/Users/admin/Downloads/code/code_temp/iOS/'
traverse_folder_and_convert_cs_files(folder_path)