编写程序,产生100个两位正的随机整数,将他们存入文件num1.txt,然后再从文件num1.txt中读取数据到一个列表中按照从小到大的排序后输出,并将排序结果写入文件num2.txt中。
时间: 2024-02-20 09:57:20 浏览: 16
好的,我可以帮你写一个Python程序来完成这个任务。以下是代码实现:
```python
import random
# 产生100个两位正的随机整数
num_list = []
for i in range(100):
num_list.append(random.randint(10, 99))
# 将数据存入文件num1.txt
with open('num1.txt', 'w') as f:
for num in num_list:
f.write(str(num) + '\n')
# 从文件num1.txt中读取数据到一个列表中
with open('num1.txt', 'r') as f:
num_list = [int(line.strip()) for line in f.readlines()]
# 按照从小到大的排序
num_list.sort()
# 输出排序结果并将排序结果写入文件num2.txt中
with open('num2.txt', 'w') as f:
for num in num_list:
print(num)
f.write(str(num) + '\n')
```
你可以运行这段代码来测试它是否可以正常工作。记得在运行前创建一个空的num1.txt文件。如果你有任何问题,请随时问我。
相关问题
编写程序,产生n个三位随机正整数,将他们存入文件num1.txt中,然后再把文件num1.txt中的数据读取到一个列表中,并排序后再存入文件num1.txt中。文件num1.txt中的原始数据和排序后的数据 之间用========隔开。
好的,以下是Python代码实现:
```python
import random
n = int(input("请输入要生成的三位随机正整数的个数:"))
# 生成n个三位随机正整数
nums = []
for i in range(n):
num = random.randint(100, 999)
nums.append(num)
# 将生成的随机数写入文件
with open("num1.txt", "w") as f:
for num in nums:
f.write(str(num) + "\n")
# 读取文件中的数据到列表中并排序
with open("num1.txt", "r") as f:
nums = [int(num.strip()) for num in f.readlines()]
nums.sort()
# 将排序后的数据写入文件
with open("num1.txt", "w") as f:
for num in nums:
f.write(str(num) + "\n")
f.write("========\n")
for num in nums:
f.write(str(num) + "\n")
print("数据已写入文件num1.txt并排序完成。")
```
这个程序首先让用户输入要生成的三位随机正整数的个数,然后使用`random.randint()`函数生成n个三位随机正整数,并将它们存入名为`num1.txt`的文件中。然后,程序再次打开`num1.txt`文件,读取其中的数据到一个列表中,并对这个列表进行排序。最后,程序将排序后的数据再次写入`num1.txt`文件,并在原始数据和排序后的数据之间添加一行分隔符`========`。
编写程序,产生100个两位正的随机整数. 将他们存入文件d:\num1.txt. 然后再从文 件d:\num1.txt 中读取数据到一个数组中按照从小到大的排序后输出,并将排序结果写入文件d:num2.txt中python
以下是Python代码实现:
```python
import random
# 产生100个两位正整数并写入文件
with open('d:\\num1.txt', 'w') as f:
for i in range(100):
num = random.randint(10, 99)
f.write(str(num) + '\n')
# 从文件中读取数据到数组中并排序
nums = []
with open('d:\\num1.txt', 'r') as f:
for line in f:
nums.append(int(line.strip()))
nums.sort()
# 将排序结果写入文件
with open('d:\\num2.txt', 'w') as f:
for num in nums:
f.write(str(num) + '\n')
# 输出排序结果
print(nums)
```
运行后会在d盘下生成num1.txt和num2.txt文件,分别存储随机整数和排序后的结果。同时在控制台输出排序结果。
相关推荐
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.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)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![text/x-c](https://img-home.csdnimg.cn/images/20210720083646.png)
![c](https://img-home.csdnimg.cn/images/20210720083646.png)