编写程序,将整数列表数据[1,2,3,4,5,6,7,8,9],按4字节整数存储到二进制文件digit.dat中
时间: 2023-09-02 13:06:18 浏览: 218
可以使用 Python 的 struct 模块来实现将整数列表按照指定的格式转换为二进制数据,并将其写入到文件中。具体实现代码如下:
```python
import struct
data = [1, 2, 3, 4, 5, 6, 7, 8, 9]
with open('digit.dat', 'wb') as f:
for d in data:
f.write(struct.pack('i', d))
```
这里使用了 struct 模块的 pack() 函数来将整数按照指定的格式转换为二进制数据,'i' 表示格式化为 4 字节的整数。然后使用文件操作中的 write() 方法将转换后的二进制数据写入到文件中。注意,这里使用的是二进制模式打开文件,即 'wb',这样可以保证写入的是二进制数据,而不是文本数据。
阅读全文
相关推荐


















