如何一下子把不同编码的文件转为utf8保存
时间: 2024-01-11 22:05:58 浏览: 30
可以使用一些文本编辑器或者编程语言提供的接口来进行批量转换编码格式。以下是使用Python进行批量转换的示例代码:
```python
import os
import codecs
def convert_encoding(file_path, from_encoding, to_encoding='utf-8'):
with codecs.open(file_path, 'r', from_encoding) as f:
content = f.read()
with codecs.open(file_path, 'w', to_encoding) as f:
f.write(content)
def batch_convert_encoding(folder_path, from_encoding, to_encoding='utf-8'):
for root, dirs, files in os.walk(folder_path):
for file in files:
file_path = os.path.join(root, file)
try:
convert_encoding(file_path, from_encoding, to_encoding)
except:
print(f'Failed to convert {file_path}.')
# 例子:将文件夹下所有 GB2312 编码的文件转为 UTF-8 编码
batch_convert_encoding('/path/to/folder', 'gb2312')
```
这段代码会将指定文件夹下所有指定编码的文件转为 UTF-8 编码并保存。