如何批量将编码GB2312转为uft-8python
时间: 2024-04-11 12:28:52 浏览: 39
您使用Python的`codecs`模块来进行批量编码转换。下面是一个将GB2312编码的文件转换为UTF-8编码的示例代码:
```python
import codecs
import os
def convert_encoding(file_path, from_encoding, to_encoding):
try:
with codecs.open(file_path, 'r', encoding=from_encoding) as file:
content = file.read()
with codecs.open(file_path, 'w', encoding=to_encoding) as file:
file.write(content)
print(f"Converted {file_path} from {from_encoding} to {to_encoding}")
except IOError as e:
print(f"Error converting {file_path}: {e}")
def batch_convert_encoding(directory, from_encoding, to_encoding):
for root, dirs, files in os.walk(directory):
for file in files:
file_path = os.path.join(root, file)
convert_encoding(file_path, from_encoding, to_encoding)
# 使用示例
batch_convert_encoding('your_directory', 'gb2312', 'utf-8')
```
请将`your_directory`替换为包含您要转换的文件的目录路径。此代码将遍历目录及其子目录中的所有文件,并将其从GB2312编码转换为UTF-8编码。转换后的文件将覆盖原始文件,请确保在运行代码之前备份文件。
阅读全文