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

Python多split报错求助:文件间数字排序问题

Fixing File Number Sorting with Split Errors

Hey there! Let's get your file number sorting working right. I see you ran into split-related issues with your code—let's walk through what went wrong and how to fix it.

First, let's recap your goal: take a file x with content like (5,6,3,11,7), sort those numbers, and write the sorted result in the same format to file y (so you get (3,5,6,7,11)).

What's Wrong with Your Current Code?

Looking at your code snippet, a couple key issues jump out:

  • You tried using n.split(...) where n is an integer (the loop index from range(len(cad))). Integers don't have a split() method—this is definitely causing errors!
  • readlines() reads each line of the file into a list, but if your file only has one line (like your example), using read() to grab the entire content at once is simpler.
  • You didn't handle the parentheses in the input content, which would mess up splitting numbers correctly.

Working Solution Code

Here's a corrected version that does exactly what you need, with comments explaining each step:

from sys import argv

# Make sure we get the two required file arguments
if len(argv) != 3:
    print("Usage: python sort_numbers.py <input_file> <output_file>")
    exit(1)

input_file = argv[1]
output_file = argv[2]

try:
    # Read the entire content of the input file
    with open(input_file, "r") as f:
        content = f.read().strip()  # Strip any leading/trailing whitespace (like newlines)
    
    # Remove the parentheses from the start and end
    cleaned_content = content[1:-1]
    
    # Split the string into individual number strings using commas as separators
    num_strings = cleaned_content.split(",")
    
    # Convert each string to an integer, then sort the list
    numbers = [int(num.strip()) for num in num_strings]  # Strip whitespace from each number string
    numbers.sort()
    
    # Format the sorted numbers back into the (num1,num2,...) string format
    sorted_content = f"({','.join(map(str, numbers))})"
    
    # Write the result to the output file
    with open(output_file, "w") as f:
        f.write(sorted_content)
    
    print(f"Successfully sorted numbers and wrote to {output_file}")

except FileNotFoundError:
    print(f"Error: The file {input_file} doesn't exist.")
except ValueError:
    print("Error: The input file contains non-numeric values.")
except Exception as e:
    print(f"An unexpected error occurred: {e}")

How This Works

Let's break down the key steps:

  1. Command Line Args Check: We first make sure the user provided both input and output file paths—no more guessing which argument is which!
  2. Clean Input Content: We strip whitespace, remove the surrounding parentheses, so we're left with just 5,6,3,11,7.
  3. Split & Convert: Using split(",") gives us a list of number strings, which we convert to integers. We also strip any extra whitespace (in case your file has spaces like (5, 6, 3)).
  4. Sort & Format: After sorting the integers, we convert them back to strings, join them with commas, and wrap the whole thing in parentheses to match your desired output format.
  5. Error Handling: Added basic error handling for missing files, non-numeric values, and other unexpected issues—so you get clear feedback if something goes wrong.

Testing with Your Example

If your input file x has (5,6,3,11,7), running python sort_numbers.py x y will create file y with (3,5,6,7,11)—exactly what you wanted!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 06:30:02