请借助struct模块将下述circles列表及其内部数据打包并存人一个二进制文件中,然后再从二进制文件读出,结果为一个新的列表circles2。遍历打印 circles2列表内的数据。要求:程序应能兼容circles列表内部元素个数不同的情况。 class Circle: def init__( self, center , radius ) : self.xCenter , self.yCenter =center self . radius = radius circles=[ ] circles.append(Circle((3.2,0.1),15.7)) circles.append(Circle((0 ,0),0.75)) circles.append(Circle((0.1,2.2),100.24))
时间: 2023-06-07 11:11:41 浏览: 68
很高兴为您解答问题。下面是代码:
```python
import struct
class Circle:
def __init__(self, center, radius):
self.xCenter, self.yCenter = center
self.radius = radius
circles = []
circles.append(Circle((3.2,0.1),15.7))
circles.append(Circle((0,0),0.75))
circles.append(Circle((0.1,2.2),100.24))
# 将circles列表打包为二进制
with open("circles.bin", "wb") as f:
for c in circles:
data = struct.pack("dd", c.xCenter, c.yCenter) + struct.pack("d", c.radius)
f.write(data)
# 从二进制文件中读取circles2列表
circles2 = []
with open("circles.bin", "rb") as f:
while True:
data = f.read(16)
if not data:
break
xCenter, yCenter = struct.unpack("dd", data[:16])
radius, = struct.unpack("d", data[16:])
circles2.append(Circle((xCenter, yCenter), radius))
# 遍历打印circle2列表内的数据
for c in circles2:
print("center: ({}, {}), radius: {}".format(c.xCenter, c.yCenter, c.radius))
```
注:程序中用到了 struct 模块将 Circle 类的对象打包为二进制数据并存储到文件中,然后再从文件中读取二进制数据解析为 Circle 类的对象并加入到 circles2 列表中。程序可以兼容 Circle 类的对象个数不同的情况。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)