File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ # 读写二进制文件
2+
3+ Python 不仅支持文本文件的读写,也支持二进制文件的读写,比如图片,声音文件等。
4+
5+ # 读取二进制文件
6+
7+ 读取二进制文件使用 'rb' 模式。
8+
9+ 这里以图片为例:
10+
11+ ``` python
12+ with open (' test.png' , ' rb' ) as f:
13+ image_data = f.read() # image_data 是字节字符串格式的,而不是文本字符串
14+ ```
15+
16+ 这里需要注意的是,在读取二进制数据时,返回的数据是字节字符串格式的,而不是文本字符串。一般情况下,我们可能会对它进行编码,比如 [ base64] ( https://en.wikipedia.org/wiki/Base64 ) 编码,可以这样做:
17+
18+ ``` python
19+ import base64
20+
21+ with open (' test.png' , ' rb' ) as f:
22+ image_data = f.read()
23+ base64_data = base64.b64encode(image_data) # 使用 base64 编码
24+ print base64_data
25+ ```
26+
27+ 下面是执行结果的一部分:
28+
29+ ``` python
30+ iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAYAAABccqhmAAAACGFjVEw
31+ ```
32+
33+ # 写入二进制文件
34+
35+ 写入二进制文件使用 'wb' 模式。
36+
37+ 以图片为例:
38+
39+ ``` python
40+ with open (' test.png' , ' rb' ) as f:
41+ image_data = f.read()
42+
43+ with open (' /Users/ethan/test2.png' , ' wb' ) as f:
44+ f.write(image_data)
45+ ```
46+
47+
48+ # 小结
49+
50+ - 读取二进制文件使用 'rb' 模式。
51+ - 写入二进制文件使用 'wb' 模式。
52+
53+ # 参考资料
54+
55+ - [ 读写字节数据 — python3-cookbook 2.0.0 文档] ( http://python3-cookbook.readthedocs.io/zh_CN/latest/c05/p04_read_write_binary_data.html )
56+
57+
You can’t perform that action at this time.
0 commit comments