Python实现整数文件排序:从data.txt到data_asc.txt
Python实现整数文件排序:从data.txt到data_asc.txt
本教程将引导您使用Python编写一个程序,该程序可以读取文本文件'data.txt'中的整数,对其进行降序排序,并将排序后的结果写入到新的文本文件'data_asc.txt'中。
以下是完整的Python代码:
# 读取数据
with open('data.txt', 'r') as file:
numbers = [int(line.strip()) for line in file]
# 排序
numbers.sort(reverse=True)
# 写入文件
with open('data_asc.txt', 'w') as file:
for number in numbers:
file.write(str(number) + '
')
print('处理完成!已将排序后的结果保存到data_asc.txt文件中。')
代码说明:
- 读取数据:
- 使用
open('data.txt', 'r')打开 'data.txt' 文件,以只读模式打开。 - 使用列表推导式
[int(line.strip()) for line in file]读取文件中的每一行,去除空格并转换为整数,存储在numbers列表中。
- 使用
- 排序:
- 使用
numbers.sort(reverse=True)对numbers列表进行降序排序。
- 使用
- 写入文件:
- 使用
open('data_asc.txt', 'w')创建并打开 'data_asc.txt' 文件,以写入模式打开。 - 循环遍历排序后的
numbers列表,将每个数字转换为字符串,并在末尾添加换行符,写入到 'data_asc.txt' 文件中。
- 使用
- 输出提示:
- 使用
print()函数输出提示信息,告知用户程序已完成。
- 使用
使用方法:
- 确保在与Python脚本相同的目录下创建名为 'data.txt' 的文本文件,并将需要排序的整数逐行写入其中。
- 运行Python脚本。
- 程序执行完成后,您将在同一目录下找到一个名为 'data_asc.txt' 的新文件,其中包含按降序排列的整数。
希望本教程能够帮助您理解如何使用Python对文本文件中的整数进行排序!
原文地址: https://www.cveoy.top/t/topic/UOl 著作权归作者所有。请勿转载和采集!