Skip to content

Python 实战:对文件中的数字进行排序

要求

有一个txt格式的文件 source.txt ,内容是一行一个数字:

123
456
134
9871
-1
12389
812
1

对这个文件中的数字进行从小到大排序,排序结果写到 target.txt 文件中,每行一个数字。

思路

  • 读 source.txt 文件内容,解析出每一个数字到 python 列表中。
  • 使用 python 内置的函数对这一堆数字进行排序。
  • 将排序结果写到 target.txt 文件中。

实现

代码文件名 number_sorter.py,实现如下:

python
def sort_numbers(source_file='source.txt', target_file='target.txt'):  #定义主函数sort_numbers,用于完成数字排序任务
    numbers = []                                    #创建空列表以存储从文件读取的数字
    try:
        with open(source_file, 'r') as f:           #打开源文件
            for line in f:
                line = line.strip()                 #移除首尾空白字符
                if line:                            #检查是否为非空行
                    try:
                        num = int(line)             #尝试将整行转换为数字
                        numbers.append(num)
                    except ValueError:
                        print(f"警告:跳过非数字内容 '{line}'")
    except FileNotFoundError:
        print(f"错误:找不到文件 {source_file}")      #处理源文件不存在的情况
        return
    numbers.sort()                                  #对数字列表进行升序排序
    try:                                            #将排序结果写入目标文件
        with open(target_file, 'w') as f:
            for num in numbers:
                f.write(f"{num}\n")
        print(f"排序完成!结果已保存到 {target_file}")
    except IOError:
        print(f"错误:无法写入文件 {target_file}")


if __name__ == '__main__':                          #定义脚本执行入口
    sort_numbers()

执行执行后,会生成文件 target.txt ,文件内容:

-1
1
123
134
456
812
9871
12389