python编写一个程序,分别将一个数字、字符串、列表、元组、字典和集合写入一个二进制文件 bFile.dat 中,然后从二进制文件 bFile.dat 中读出并显示。
时间: 2024-02-07 17:03:22 浏览: 103
可以使用以下代码实现:
```python
import pickle
# 定义要写入的数据
num = 123
string = 'hello'
lst = [1, 2, 3]
tp = (4, 5, 6)
dic = {'name': 'Tom', 'age': 18}
s = {7, 8, 9}
# 将数据写入二进制文件 bFile.dat 中
with open('bFile.dat', 'wb') as f:
pickle.dump(num, f)
pickle.dump(string, f)
pickle.dump(lst, f)
pickle.dump(tp, f)
pickle.dump(dic, f)
pickle.dump(s, f)
# 从二进制文件 bFile.dat 中读出数据并显示
with open('bFile.dat', 'rb') as f:
num = pickle.load(f)
string = pickle.load(f)
lst = pickle.load(f)
tp = pickle.load(f)
dic = pickle.load(f)
s = pickle.load(f)
print(num) # 输出:123
print(string) # 输出:hello
print(lst) # 输出:[1, 2, 3]
print(tp) # 输出:(4, 5, 6)
print(dic) # 输出:{'name': 'Tom', 'age': 18}
print(s) # 输出:{8, 9, 7}
```
首先,我们使用 pickle 模块将数字、字符串、列表、元组、字典和集合写入二进制文件 bFile.dat 中。然后,我们使用 pickle.load() 方法从二进制文件 bFile.dat 中读出数据,并将其分别赋值给 num、string、lst、tp、dic 和 s 变量。最后,我们输出这些变量的值,可以看到它们分别对应着我们定义的数字、字符串、列表、元组、字典和集合。
阅读全文
相关推荐















