编写程序,将整数列表数据[1,2,3,4,5,6,7,8,9],按4字节整数存储到二进制文件digit.dat中。
时间: 2023-09-02 15:06:18 浏览: 180
可以使用Python内置的struct模块来实现将整数列表存储到二进制文件中的功能。struct模块提供了将数据转换为C语言风格的二进制数据格式的函数,可以方便地将Python数据类型转换为二进制数据。
以下是示例代码:
```python
import struct
def write_integers_to_binary_file(numbers, file_path):
with open(file_path, mode='wb') as binary_file:
for number in numbers:
# 将整数转换为4字节二进制数据
binary_data = struct.pack('i', number)
# 将二进制数据写入文件
binary_file.write(binary_data)
# 示例用法
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
file_path = 'digit.dat'
write_integers_to_binary_file(numbers, file_path)
```
在示例代码中,`write_integers_to_binary_file`函数接受一个整数列表和一个文件路径作为参数。使用`with`语句打开文件,并将文件对象赋值给`binary_file`变量。然后使用`struct.pack`函数将每个整数转换为4字节的二进制数据,并将二进制数据写入文件。最后使用`with`语句块结束后,文件会自动关闭。
你可以将以上代码保存为.py文件并运行测试。程序会将整数列表[1,2,3,4,5,6,7,8,9]按4字节整数存储到二进制文件digit.dat中。
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![ppt](https://img-home.csdnimg.cn/images/20241231044937.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![](https://img-home.csdnimg.cn/images/20250102104920.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pptx](https://img-home.csdnimg.cn/images/20241231044947.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)