Python实现整数降序排序并写入文件

本教程将演示如何使用Python编写程序,实现以下功能:

  1. 从文本文件 'data.txt' 中读取若干整数,每个整数占一行。
  2. 对所有读取的整数进行降序排序。
  3. 将排序后的整数写入到另一个文本文件 'data_asc.txt' 中,每个整数占一行。

以下是完整的Python代码:

def sort_integers(input_file, output_file):
    # 读取输入文件中的整数列表
    with open(input_file, 'r') as file:
        integers = [int(line.strip()) for line in file.readlines()]

    # 对整数列表进行降序排序
    sorted_integers = sorted(integers, reverse=True)

    # 将排序后的整数列表写入输出文件
    with open(output_file, 'w') as file:
        file.writelines([str(integer) + '\n' for integer in sorted_integers])

# 输入和输出文件名
input_file = 'data.txt'
output_file = 'data_asc.txt'

# 调用函数进行排序并写入输出文件
sort_integers(input_file, output_file)

使用方法:

  1. 将以上代码保存为名为 'sort_integers.py' 的Python文件。
  2. 在与 'sort_integers.py' 相同的目录下,创建一个名为 'data.txt' 的文本文件,并在其中输入要排序的整数,每个整数占一行。
  3. 打开命令行终端,进入到 'sort_integers.py' 和 'data.txt' 所在的目录。
  4. 运行命令 python sort_integers.py

程序执行完毕后,将会在相同目录下生成一个名为 'data_asc.txt' 的文件,其中包含了 'data.txt' 中所有整数的降序排序结果。

代码解释:

  1. sort_integers(input_file, output_file) 函数:
    • 接收两个参数,分别是输入文件名和输出文件名。
    • 使用 with open(...) as file: 语句打开文件,确保文件在使用完毕后自动关闭。
    • 使用列表推导式 [int(line.strip()) for line in file.readlines()] 读取所有整数并转换为整数类型。
    • 使用 sorted(integers, reverse=True) 对整数列表进行降序排序。
    • 使用 file.writelines(...) 将排序后的整数列表写入输出文件,每个整数占一行。
  2. 主程序部分:
    • 定义输入文件名和输出文件名。
    • 调用 sort_integers() 函数执行排序和写入操作。

原文地址: https://www.cveoy.top/t/topic/UOi 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录