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

如何用Python结合命令行参数提取文本文件指定列内容

Alright, let's put together a Python script that does exactly what you need—pulling specific columns from text files using command-line arguments. Here's a robust, easy-to-use solution:

Python Script for Extracting Specific Columns from Text Files

First, save this code as my_program.py:

import sys

def extract_column(column_num, file_path):
    # Convert 1-based column input to 0-based index (Python uses 0-indexing)
    column_index = column_num - 1
    try:
        with open(file_path, 'r') as file:
            for line in file:
                # Split line into columns (handles any whitespace separators: spaces, tabs)
                columns = line.strip().split()
                if column_index < len(columns):
                    print(columns[column_index])
                else:
                    print(f"Warning: This line has fewer than {column_num} columns")
    except FileNotFoundError:
        print(f"Error: Couldn't find the file '{file_path}'")
    except Exception as e:
        print(f"Unexpected error: {str(e)}")

if __name__ == "__main__":
    # Validate command-line arguments count
    if len(sys.argv) != 3:
        print("Usage: python my_program.py <column_number> <file_path>")
        print("Example: python my_program.py 1 fruits.txt")
        sys.exit(1)
    
    # Parse and validate column number
    try:
        target_column = int(sys.argv[1])
        if target_column < 1:
            print("Error: Column number must be a positive integer (1, 2, 3...)")
            sys.exit(1)
    except ValueError:
        print("Error: Column number needs to be a valid integer")
        sys.exit(1)
    
    # Run the extraction
    file_path = sys.argv[2]
    extract_column(target_column, file_path)

How This Script Works

Let's break down the key bits so you know what's happening under the hood:

  • Command Line Argument Handling: Uses sys.argv to grab your input column number and file path. It first checks you've provided exactly two arguments (plus the script name), otherwise it shows a clear usage guide.
  • Index Conversion: Since Python lists start at 0, we subtract 1 from your input column number to match the correct position in the split line.
  • Safe File Reading: The with statement ensures the file is automatically closed after processing, even if an error occurs.
  • Flexible Column Splitting: split() handles any amount of whitespace (spaces, tabs) between columns, so it works for consistent formatted files like your fruits.txt or veg.txt.
  • Error Handling: Catches common issues like missing files, non-integer column inputs, or lines that don't have enough columns, so you get clear feedback instead of a cryptic crash.

Example Usage

Test it with your fruits.txt content:

Apple Pear Watermelon
Orange Grapes Banana

Running python my_program.py 1 fruits.txt outputs:

Apple
Orange

Running python my_program.py 3 fruits.txt outputs:

Watermelon
Banana

This script works seamlessly with any whitespace-separated text file (like veg.txt) as long as you follow the same command-line format.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:25:09