有许多以前的TXT格式的书籍,由于里面的中文字符编码不是UTF-8,所以只能在电脑上阅读才能正常显示,而放在网上在线阅读时,总是一堆乱码。
为了更方便的阅读,需要将这些txt文件的编码转换成UTF-8。由于文件太多。需要进行批量转换。用 Python 脚本来实现这一功能是一个不错的办法。
首先需要在电脑上下载并安装好Python。我这是windows11系统的电脑所以用的是这个python-3.13.2-amd64.exe.安装时要记得勾选 “Add Python to PATH” 选项。
安装好Python后,再需要在命令行安装chardet库。进入Python安装目录的Scripts目录下,我的是这里:C:\Users\Administrator\AppData\Local\Programs\Python\Python313\Scripts
在浏览器地址栏输入cmd,进入命令模式输入:
pip install chardet
这样就安装完成了。
然后用代码编辑器写好脚本并保存为your.py文件。
import os
import chardet
def convert_to_utf8(file_path):
try:
with open(file_path, 'rb') as file:
raw_data = file.read()
result = chardet.detect(raw_data)
encoding = result['encoding']
if encoding.lower() != 'utf-8':
content = raw_data.decode(encoding, errors='ignore')
with open(file_path, 'w', encoding='utf-8') as new_file:
new_file.write(content)
print(f'{file_path} 已从 {encoding} 转换为 UTF - 8')
else:
print(f'{file_path} 已经是 UTF - 8 编码')
except FileNotFoundError:
print(f'文件 {file_path} 未找到。')
except PermissionError:
print(f'没有权限访问文件 {file_path}。')
except UnicodeDecodeError as ude:
print(f'解码文件 {file_path} 时出错: {ude}')
except Exception as e:
print(f'处理 {file_path} 时发生未知错误: {e}')
def batch_convert(folder_path):
try:
for root, dirs, files in os.walk(folder_path):
for file in files:
if file.endswith('.txt'):
file_path = os.path.join(root, file)
convert_to_utf8(file_path)
except FileNotFoundError:
print(f'文件夹 {folder_path} 未找到。')
except PermissionError:
print(f'没有权限访问文件夹 {folder_path}。')
except Exception as e:
print(f'处理文件夹 {folder_path} 时发生未知错误: {e}')
if __name__ == "__main__":
folder_path = r'your_folder_path' # 请替换为包含 TXT 文件的文件夹路径
batch_convert(folder_path)
进入you.py文件目录运行它就可以了。
这段代码能够递归地对指定目录下的多级子目录中的所有 .txt 文件进行编码转换。
本文为原创文章,版权归旷野小站所有,欢迎分享本文,转载请保留出处!