You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:Python合并两个文本文件整数并排序保存的实现方法

Fixing the Sorting Issue for Merged Number Files

Hey there! I see the problem with your current code—it’s just dumping the raw content of both files into all_numbers.txt without actually processing the numbers to sort them. Let’s fix that up so your final file has all integers in clean ascending order.

What’s Off with the Original Code?

Your current code copies text directly from each input file, which preserves the messy, unsorted order of numbers in both numbers1.txt and numbers2.txt and just sticks them end-to-end. We need to:

  1. Read every number from both files as actual integers (not just text)
  2. Gather all these numbers into a single list
  3. Sort the list properly
  4. Write the sorted numbers to all_numbers.txt

Updated Working Code

# List of input files to process
filenames = ['numbers1.txt', 'numbers2.txt']
all_numbers = []

# Read and parse numbers from each file
for filename in filenames:
    with open(filename, 'r') as infile:
        # Split file content into number strings, then convert each to integer
        numbers = [int(num_str) for num_str in infile.read().split()]
        all_numbers.extend(numbers)

# Sort all collected numbers in ascending order
all_numbers.sort()

# Write the sorted result to the output file
with open('all_numbers.txt', 'w') as outfile:
    # Convert integers back to strings and join with spaces (matching input format)
    outfile.write(' '.join(str(num) for num in all_numbers))

print("Your file is saved under all_numbers.txt")

How This Works

  • Parsing Numbers: We use split() to break the file’s text into individual number strings, then convert each to an integer with a list comprehension. This handles spaces and any accidental newlines in your input files.
  • Collecting All Numbers: The extend() method adds every number from each file to our main all_numbers list, giving us one big collection of all integers.
  • Sorting: The sort() method sorts the list in-place in ascending order (the default behavior for integers).
  • Writing the Result: We convert the sorted integers back to strings, join them with spaces (to match your input file format), and write the entire string to all_numbers.txt.

After running this code, your all_numbers.txt will contain:
10 20 30 40 50 60 80 100 101 150 999

内容的提问来源于stack exchange,提问作者user12739323

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 10:07:32