# filepath -- 原文件路径
# savefilepath -- 转换后文件存储路径(默认 = 原文件路径)
# oldencoding -- 原文件的编码格式
# newencoding -- 转换后文件的编码格式
import os
import time
def convert_xml_encoding(filepath, savefilepath, oldencoding, newencoding):
# Read the XML file
with open(filepath, 'rb') as file:
content = file.read()
decoded_content = content.decode(oldencoding, errors='ignore')
updated_content = decoded_content.replace('encoding="{}"'.format(oldencoding),
'encoding="{}"'.format(newencoding))
encoded_content = updated_content.encode(newencoding,errors='ignore')
with open(savefilepath, 'wb') as file:
file.write(encoded_content)
print(f"XML file '{os.path.basename(filepath)}'({oldencoding}) --> '{os.path.basename(savefilepath)}'({newencoding})")
# ---------------------- 使用示例 ---------------------
# GBK --> utf-8
convert_xml_encoding('F:\CHEN\PYQT5CLIENT\ABCD\ErrorResult.xml', 'F:\CHEN\PYQT5CLIENT\ABCD\ErrorResult.xml', 'GBK', 'utf-8')