12.15:如果名为Exercies12_15.txt的文件不存在,则创建该文件。使用文本I/O将随机产生的100个整数写入文件,文件中的整数由空格分开。从文件中读回数据并以升序显示数据。
时间: 2024-02-20 09:58:31 浏览: 20
好的,我会为您解答这个问题。
首先,您需要使用Python中的`random`库来生成100个随机整数。然后,您可以使用Python中的`os`库来检查文件是否存在,并且使用`open()`函数创建一个文件对象,以便写入数据。接下来,您可以使用`write()`方法将整数写入文件中,每个整数之间用空格分隔。
下面是实现上述操作的代码示例:
```python
import random
import os
# 生成100个随机整数
random_numbers = [random.randint(1, 100) for _ in range(100)]
# 检查文件是否存在,如果不存在则创建文件
if not os.path.exists("Exercies12_15.txt"):
open("Exercies12_15.txt", "w").close()
# 打开文件并写入随机整数
with open("Exercies12_15.txt", "w") as file:
file.write(" ".join(str(num) for num in random_numbers))
# 从文件中读取数据并以升序显示数据
with open("Exercies12_15.txt", "r") as file:
numbers = file.read().split()
sorted_numbers = sorted(map(int, numbers))
print(sorted_numbers)
```
上面的代码将生成100个随机整数,将它们写入文件,然后读取文件中的数据并按升序显示它们。