Python实现整数文件降序排序

本文提供了一个Python代码示例,用于读取文件'data.txt'中的整数,将其按降序排序,并将结果保存到新的文件'data_asc.txt'中。

代码示例:

import os

# 读取整数列表
numbers = []
file_path = os.path.expanduser('~/Desktop/data.txt')  # 将'~'替换为你的用户名
with open(file_path, 'r') as file:
    for line in file:
        number = int(line.strip())
        numbers.append(number)

# 按降序排序
numbers.sort(reverse=True)

# 写入降序后的整数到文件中
output_file_path = os.path.expanduser('~/Desktop/data_asc.txt')  # 将'~'替换为你的用户名
with open(output_file_path, 'w') as output_file:
    for number in numbers:
        output_file.write(str(number) + '
')

print('整数已按降序写入文件data_asc.txt')

代码解释:

  1. 导入os模块: 用于处理文件路径,特别是os.path.expanduser()函数可以将~替换为用户的主目录路径。
  2. 读取整数:
    • file_path变量存储了'data.txt'文件的完整路径。
    • 使用with open(...) as file语句打开文件,确保文件在使用后自动关闭。
    • 循环读取文件中的每一行,使用int(line.strip())将每一行转换为整数并添加到numbers列表中。
  3. 降序排序: 使用numbers.sort(reverse=True)numbers列表进行降序排序。
  4. 写入文件:
    • output_file_path变量存储了'data_asc.txt'文件的完整路径。
    • 类似读取文件,使用with open(...) as output_file语句打开文件进行写入。
    • 循环遍历排序后的numbers列表,将每个整数转换为字符串后写入文件,并使用 换行。
  5. 输出信息: 打印提示信息,告知用户整数已写入文件。

请确保将代码中的~/Desktop/data.txt~/Desktop/data_asc.txt路径中的~替换为你的实际用户名,以便代码能够正确找到文件。

Python实现整数文件排序:降序排列data.txt

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

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