python分别使用pickle和struct 写入和读取二进制文件
时间: 2024-02-28 09:55:59 浏览: 149
使用 pickle 写入和读取二进制文件的示例代码如下:
写入:
```
import pickle
data = {"name": "Tom", "age": 18}
# 将数据写入二进制文件
with open("data.bin", "wb") as f:
pickle.dump(data, f)
```
读取:
```
import pickle
# 从二进制文件中读取数据
with open("data.bin", "rb") as f:
data = pickle.load(f)
print(data)
```
使用 struct 写入和读取二进制文件的示例代码如下:
写入:
```
import struct
data = {"name": "Tom", "age": 18}
# 将数据写入二进制文件
with open("data.bin", "wb") as f:
name = data["name"].encode("utf-8")
age = data["age"]
f.write(struct.pack("I", len(name)))
f.write(name)
f.write(struct.pack("I", age))
```
读取:
```
import struct
# 从二进制文件中读取数据
with open("data.bin", "rb") as f:
name_len = struct.unpack("I", f.read(4))[0]
name = f.read(name_len).decode("utf-8")
age = struct.unpack("I", f.read(4))[0]
data = {"name": name, "age": age}
print(data)
```
阅读全文