python中的base64使用方法
时间: 2024-03-30 21:14:45 浏览: 75
Python中的base64模块提供了编码和解码二进制数据的功能,通常用于在网络传输或邮件传输过程中对二进制数据进行编码和解码。下面是base64的使用方法:
1. 编码字符串
```python
import base64
s = 'Hello, world!'
b = s.encode('utf-8') # 将字符串转换为bytes类型
encoded = base64.b64encode(b)
print(encoded) # b'SGVsbG8sIHdvcmxkIQ=='
```
2. 解码字符串
```python
import base64
encoded = b'SGVsbG8sIHdvcmxkIQ=='
decoded = base64.b64decode(encoded)
s = decoded.decode('utf-8') # 将bytes类型转换为字符串
print(s) # 'Hello, world!'
```
3. 编码文件
```python
import base64
with open('example.jpg', 'rb') as f:
encoded = base64.b64encode(f.read())
with open('example_base64.txt', 'wb') as f:
f.write(encoded)
```
4. 解码文件
```python
import base64
with open('example_base64.txt', 'rb') as f:
encoded = f.read()
decoded = base64.b64decode(encoded)
with open('example_decoded.jpg', 'wb') as f:
f.write(decoded)
```
注意:在对二进制文件进行base64编码时,需要以二进制模式读取和写入文件,否则可能会导致编码出错。
阅读全文