(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 18:02:22 浏览: 27
Sure, here's an example program in Python that does what you're asking for:
```python
import random
import struct
# Open the file in binary append mode (creates a new file if it doesn't exist)
with open('Exercise17_02.dat', 'ab') as file:
# Generate 100 random integers and write them to the file
for i in range(100):
value = random.randint(0, 100)
data = struct.pack('i', value)
file.write(data)
```
Explanation:
- We use the `open()` function to open the file named `Exercise17_02.dat` in binary append mode (`'ab'`). This means that if the file already exists, we'll append new data to the end of it. If it doesn't exist, a new file with that name will be created.
- We use a `with` statement to ensure that the file is properly closed when we're done with it.
- We use the `random.randint()` function to generate a random integer between 0 and 100.
- We use the `struct.pack()` function to convert the integer value into a binary format that can be written to the file. The `'i'` format code specifies that the value should be packed as a 4-byte (32-bit) integer.
- We use the `file.write()` method to write the binary data to the file.
After running this program, you should have a file named `Exercise17_02.dat` in the current directory, containing 100 randomly generated integers in binary format.