在打开文件的情况下添加或修改编码

用 io.TextIOWrapper() 包裹一个文件对象,可以为其添加或指定编码。

>>> f = open(r'e:\path\abc.txt', 'w')
>>> f
<_io.TextIOWrapper name='e:\\path\\abc.txt' mode='w' encoding='cp936'>
>>> f.buffer
<_io.BufferedWriter name='e:\\path\\abc.txt'>
>>> f.buffer.raw
<_io.FileIO name='e:\\path\\abc.txt' mode='wb' closefd=True>
>>> b = f.detach()
>>> b
<_io.BufferedWriter name='e:\\path\\abc.txt'>
>>> f.write('hello')
Traceback (most recent call last):
  File "<pyshell#24>", line 1, in <module>
    f.write('hello')
ValueError: underlying buffer has been detached
>>> f = io.TextIOWrapper(b, encoding='latin-1')
>>> f
<_io.TextIOWrapper name='e:\\path\\abc.txt' encoding='latin-1'>
>>> f.write('hello')
5
>>> f.write('我爱python')
Traceback (most recent call last):
  File "<pyshell#28>", line 1, in <module>
    f.write('我爱python')
UnicodeEncodeError: 'latin-1' codec can't encode characters in position 0-1: ordinal not in range(256)


1. io.TextIOWrapper 是一个编码和解码的文本处理层。

2. io.BufferedWriter 是一个缓冲的 I/O 层,用于处理二进制数据。

3. io.FileIO 是一个原始文件,表示操作系统中的底层文件描述。

4. f.detach() 将文本层和缓冲层分离,此时或关闭文件。

5. io.TextIOWrapper(b, encoding) 定义带编码的文本处理层。

6. 编码无法编译的会抛出异常。


使用 openurl() 请求网络资源时指定编码

import urllib.request
import io

u = urllib.request.urlopen('http://www.python.org')
f = io.TextIOWrapper(u,encoding='utf-8')
text = f.read() 

展开阅读全文