Skip to content

Commit bbb8e25

Browse files
committed
add 5.16 增加或改变已打开文件的编码
1 parent 4b133a3 commit bbb8e25

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
# 5.16 增加或改变已打开文件的编码
2+
3+
## 问题
4+
5+
你想在不关闭一个已打开的文件前提下增加或改变它的Unicode编码。
6+
7+
## 解决方案
8+
9+
如果你想给一个以二进制模式打开的文件添加Unicode编码/解码方式, 可以使用 `io.TextIOWrapper()` 对象包装它。比如:
10+
11+
```python
12+
import urllib.request
13+
import io
14+
15+
u = urllib.request.urlopen('http://www.python.org')
16+
f = io.TextIOWrapper(u, encoding='utf-8')
17+
text = f.read()
18+
```
19+
20+
如果你想修改一个已经打开的文本模式的文件的编码方式,可以先使用 `detach()` 方法移除掉已存在的文本编码层, 并使用新的编码方式代替。下面是一个在 `sys.stdout` 上修改编码方式的例子:
21+
22+
```python
23+
>>> import sys
24+
>>> sys.stdout.encoding
25+
'UTF-8'
26+
>>> sys.stdout = io.TextIOWrapper(sys.stdout.detach(), encoding='latin-1')
27+
>>> sys.stdout.encoding
28+
'latin-1'
29+
>>>
30+
```
31+
32+
这样做可能会中断你的终端,这里仅仅是为了演示而已。
33+
34+
## 讨论

0 commit comments

Comments
 (0)