base64编码在python中的用法
时间: 2023-08-05 07:07:53 浏览: 124
在Python中,我们可以使用`base64`模块来进行base64编码和解码。这个模块提供了`b64encode()`和`b64decode()`两个函数,可以分别用于编码和解码操作。下面是一些示例代码:
1. 编码字符串:
```python
import base64
sample_string = "Hello, world!"
encoded_string = base64.b64encode(sample_string.encode('utf-8'))
print(encoded_string)
```
输出结果为:
```
b'SGVsbG8sIHdvcmxkIQ=='
```
2. 解码字符串:
```python
import base64
encoded_string = b'SGVsbG8sIHdvcmxkIQ=='
decoded_string = base64.b64decode(encoded_string).decode('utf-8')
print(decoded_string)
```
输出结果为:
```
Hello, world!
```
3. 编码文件内容:
```python
import base64
with open('sample.txt', 'rb') as file:
encoded_file = base64.b64encode(file.read())
print(encoded_file)
```
4. 解码文件内容:
```python
import base64
with open('sample.txt', 'rb') as file:
encoded_file = file.read()
decoded_file = base64.b64decode(encoded_file)
with open('decoded_sample.txt', 'wb') as file:
file.write(decoded_file)
```
阅读全文