python中对文本文件实现编码转换
时间: 2023-12-03 13:46:56 浏览: 106
在Python中,可以使用`codecs`和`io`模块来实现编码转换。具体步骤如下:
1. 打开原始文件并指定编码方式读取文本内容:
```python
import codecs
with codecs.open('filename.txt', 'r', 'old_encoding') as f:
content = f.read()
```
2. 将文本内容转换为新的编码方式:
```python
content = content.encode('new_encoding')
```
3. 写入转换后的内容到新的文件中:
```python
with codecs.open('new_filename.txt', 'w', 'new_encoding') as f:
f.write(content)
```
完整的代码示例:
```python
import codecs
# 打开原始文件并指定编码方式读取文本内容
with codecs.open('filename.txt', 'r', 'old_encoding') as f:
content = f.read()
# 将文本内容转换为新的编码方式
content = content.encode('new_encoding')
# 写入转换后的内容到新的文件中
with codecs.open('new_filename.txt', 'w', 'new_encoding') as f:
f.write(content)
```
其中,`old_encoding`表示原始文本的编码方式,`new_encoding`表示需要转换成的编码方式。常见的编码方式包括UTF-8、GBK等。