(Create a binary data file) Write a program to create a file named Exercise17_02.dat if it does not exist. Append new data to it if it already exists. Write 100 integers created randomly into the file using binary VO.
时间: 2024-02-06 08:02:17 浏览: 41
Sure, here's the Python code to create a binary data file with 100 randomly generated integers:
```python
import random
import os
filename = "Exercise17_02.dat"
if os.path.exists(filename):
mode = "ab"
else:
mode = "wb"
with open(filename, mode) as file:
for i in range(100):
num = random.randint(1, 100)
file.write(num.to_bytes(4, byteorder='big'))
```
Here's how the code works:
- First, we define the filename as `Exercise17_02.dat`.
- We then check if the file exists using the `os.path.exists()` function. If the file exists, we open it in binary append mode (`"ab"`), which means any new data we write will be added to the end of the file. If the file does not exist, we open it in binary write mode (`"wb"`), which means any existing file with the same name will be overwritten.
- We use a `with` block to open the file and ensure it is closed when we're done.
- Inside the `with` block, we use a loop to generate 100 random integers using the `random.randint()` function.
- We write each integer to the file using the `file.write()` method. To write the integer as binary data, we convert it to a byte string using the `to_bytes()` method with a byte size of 4 (since each integer takes up 4 bytes) and a byte order of "big" (which means the most significant byte is first).
This will create a binary data file with 100 randomly generated integers.
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.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)