How do you use io.BytesIO in Python?
The io.BytesIO module in Python is a tool used for reading and writing binary data in memory. Here are some examples of using io.BytesIO:
- Create an empty BytesIO object.
import io
# 创建一个空的BytesIO对象
buffer = io.BytesIO()
- Write byte data to a BytesIO object.
import io
# 创建一个空的BytesIO对象
buffer = io.BytesIO()
# 将字节数据写入BytesIO对象
buffer.write(b'Hello, World!')
- Create a BytesIO object from existing byte data.
import io
# 从已有的字节数据创建BytesIO对象
data = b'Hello, World!'
buffer = io.BytesIO(data)
- Read byte data from a BytesIO object.
import io
# 从已有的字节数据创建BytesIO对象
data = b'Hello, World!'
buffer = io.BytesIO(data)
# 从BytesIO对象中读取字节数据
result = buffer.read()
print(result) # 输出: b'Hello, World!'
- Convert the byte data in the BytesIO object into a string.
import io
# 从已有的字节数据创建BytesIO对象
data = b'Hello, World!'
buffer = io.BytesIO(data)
# 从BytesIO对象中读取字节数据并转换为字符串
result = buffer.read().decode('utf-8')
print(result) # 输出: Hello, World!
Here are some basic uses of the io.BytesIO module, you can further customize and expand based on your own needs.