import codecs
# 打开文件并进行编码转换
with codecs.open('example.txt', 'r', 'gbk') as f:
data = f.read()
with codecs.open('example.txt', 'w', 'utf-8') as f:
f.write(data)
import os
import chardet
import codecs
# 获取当前目录下所有文件
files = os.listdir()
# 要转换的编码列表,可根据需要修改
encodings = ['gbk', 'gb2312', 'utf-8']
for file in files:
# 只处理文件,跳过文件夹
if not os.path.isfile(file):
continue
# 打开文件,并检测编码
with open(file, 'rb') as f:
data = f.read()
result = chardet.detect(data)
# 检测到的编码在要转换的编码列表中,才处理
if result['encoding'] in encodings:
# 使用检测到的编码打开文件
with codecs.open(file, 'r', result['encoding']) as f:
data = f.read()
# 统一使用UTF-8编码保存文件
with codecs.open(file, 'w', 'utf-8') as f:
f.write(data)
print(f'{file} 转换完成')
import os
import chardet
import codecs
from concurrent.futures import ThreadPoolExecutor
# 获取当前目录下所有文件
files = os.listdir()
# 要转换的编码列表,可根据需要修改
encodings = ['gbk', 'gb2312', 'utf-8']
def convert_file(file):
# 只处理文件,跳过文件夹
if not os.path.isfile(file):
return
# 打开文件,并检测编码
with open(file, 'rb') as f:
data = f.read()
result = chardet.detect(data)
# 检测到的编码在要转换的编码列表中,才处理
if result['encoding'] in encodings:
# 使用检测到的编码打开文件
with codecs.open(file, 'r', result['encoding']) as f:
data = f.read()
# 统一使用UTF-8编码保存文件
with codecs.open(file, 'w', 'utf-8') as f:
f.write(data)
print(f'{file} 转换完成')
# 使用多线程处理文件转换
with ThreadPoolExecutor(max_workers=4) as executor:
executor.map(convert_file, files)
print('所有文件转换完成')
import codecs
# 打开文件并以UTF-16BE编码读取文件内容
with codecs.open('example.txt', 'r', 'utf-16be') as f:
data = f.read()
# 以UTF-8编码保存文件
with codecs.open('example.txt', 'w',