【问题标题】:How to sort numbers from two different txt files then save them as one txt file如何从两个不同的txt文件中对数字进行排序,然后将它们保存为一个txt文件
【发布时间】:2026-02-04 19:20:04
【问题描述】:

有人可以帮忙吗? 我有以下任务:

  • 在此文件夹中创建一个名为 ​combined.py 的新 Python 文件
  • 创建一个名为​numbers1.txt 的文本文件,其中包含从最小到最大排序的整数。

  • 创建另一个名为​numbers2.txt 的文本文件,其中还包含从小到大排序的整数。

  • 将两个文件中的数字写入名为​all_numbers.txt的第三个文件

  • ​all_numbers.txt中的所有数字都应该从小到大排序。

这2个txt文件如下:

数字1:

20
10
30
50
40
60

然后:

数字2:

999
80
150
101
100

下面的代码将两个txt文件正确保存为一个文件。我只是在将整数从最低到最高排序时遇到了一些麻烦。任何帮助将不胜感激!谢谢!

filenames = ['numbers1.txt', 'numbers2.txt']
with open('all_numbers.txt', 'w') as outfile:
    for a in filenames:
        with open(a) as infile:
            outfile.write(infile.read() + "\n")
print("Your file is saved under all_numbers.txt")

【问题讨论】:

    标签: python sorting output


    【解决方案1】:

    目前,您在读取每个输入文件的内容后立即将其写入输出 (outfile.write(infile.read() + "\n"))。要处理它们,我建议您先将它们读入列表,然后从那里开始工作。

    要从每个文件创建整数列表,有多种方法。一种是用.read() 将整个文件读入一个字符串,用.strip() 去除多余的空格和换行符,然后在换行符处拆分。然后,您可以使用列表推导式或映射或一些等效方法将此数字字符串列表转换为整数列表。

    然后你需要将这两个列表组合起来并排序。有很多算法可以解决这个问题。由于您的任务没有指定,您可以使用内置的sorted() 函数或列表方法.sort()。这将必须对由两个列表连接在一起的列表进行操作。要在 Python 中连接两个列表,我们只需添加它们 ([1, 2] + [3, 4] == [1, 2, 3, 4])。

    因此,您的最终解决方案可能类似于:

    filenames = ['numbers1.txt', 'numbers2.txt']
    num_lists = [[int(x) for x in open(f).read().strip().split('\n')] \
                 for f in filenames]
    with open('all_numbers.txt', 'w') as outfile:
        outfile.write('\n'.join(str(x) for x in sorted(sum(num_lists, []))) + '\n')
    
    print('Your file is saved under all_numbers.txt')
    

    请注意,sum(numbers_list, []) 等同于 numbers_list[0] + numbers_list[1],但更好,因为您的解决方案现在适用于任意数量的输入文件。 :)

    测试

    $ echo '20
    > 10
    > 30
    > 50
    > 40
    > 60' > numbers1.txt
    $ echo '999
    > 80
    > 150
    > 101
    > 100' > numbers2.txt
    $ python -q
    >>> filenames = ['numbers1.txt', 'numbers2.txt']
    >>> num_lists = [[int(x) for x in open(f).read().strip().split('\n')] \
    ...              for f in filenames]
    >>> with open('all_numbers.txt', 'w') as outfile:
    ...     outfile.write('\n'.join(str(x) for x in sorted(sum(num_lists, []))) + '\n')
    ... 
    37
    >>> print('Your file is saved under all_numbers.txt')
    Your file is saved under all_numbers.txt
    >>> 
    $ cat all_numbers.txt 
    10
    20
    30
    40
    50
    60
    80
    100
    101
    150
    999
    

    【讨论】:

      【解决方案2】:

      听起来简单的合并是最好的,我们现在将使用sorted 来保持简单。

      首先,您应该将代码模块化一点,以便每个部分的逻辑清晰。让我们使用函数将每个文件中的数字提取到一个列表中:

      def load_numbers(filepath):
          with open(filepath, 'r') as file:
              return [int(n) for n in file.readlines()]
      

      我们现在可以调用它来将我们的数字加载到列表中:

      first_numbers = load_numbers('numbers1.txt')
      second_numbers = load_numbers('numbers2.txt')
      

      现在我们需要一种方法来合并这两个列表并确保它们已排序。使用 Python 的 sorted 我们可以做到:

      sorted_numbers = sorted(first_numbers + second_numbers)
      

      Joe 的回答有一个很好的方法,可以使用 sum 将其扩展到多个列表。

      要将其写入文件,我们可以执行与读取类似的操作:

      with open('all_numbers.txt', 'w') as file:
          file.writelines(sorted_numbers)
      

      总共:

      def load_numbers(filepath):
          with open(filepath, 'r') as file:
              return [int(n) for n in file.readlines()]
      
      
      if __name__ = '__main__':
          first_numbers = load_numbers('numbers1.txt')
          second_numbers = load_numbers('numbers2.txt')
      
          sorted_numbers = sorted(first_numbers + second_numbers)
      
          with open('all_numbers.txt', 'w') as file:
              file.writelines(sorted_numbers)
      

      【讨论】:

      • +1 很好,我使用了一个巧妙的 sum() 小技巧来使解决方案适应任意数量的输入列表。
      • 啊,真聪明,不错!
      • 谢谢大家的帮助!!它运行完美!
      最近更新 更多