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

Python:如何为输出添加多列?解决路径拼接IndexError问题

解决方法:在输出路径中加入多列值

你遇到的IndexError: list out of range是因为代码中访问了不存在的列表索引——你的文件每行只有3列数据,对应索引0(姓名)、1(月份)、2(文件夹名),如果尝试访问columns[3]这类超出范围的索引就会报错。

下面是调整后的代码,把第三列(姓名,即columns[0])加入输出路径,同时做了关键优化:

import os

# 根目录,用绝对路径更可靠
root_dir = 'C:/Desktop/main_folder'

with open('file.txt', 'r') as infile:
    for line in infile:
        # 按空白分割列,自动处理多空格分隔
        columns = line.strip().split()
        # 确认每行有足够列数,避免索引错误
        if len(columns) != 3:
            print(f"跳过格式错误的行: {line}")
            continue
        # 拼接路径:根目录 -> folder列 -> 月份列 -> 姓名.txt
        path = os.path.join(root_dir, columns[2], columns[1], f"{columns[0]}.txt")
        # 创建上级文件夹(如果不存在)
        os.makedirs(os.path.dirname(path), exist_ok=True)
        # 写入文件
        with open(path, 'w') as outfile:
            outfile.write(line)

代码说明:

  • os.makedirs(..., exist_ok=True):自动创建路径中的所有上级文件夹,避免因文件夹不存在导致的FileNotFoundError
  • 加入列数检查len(columns) !=3:跳过格式异常的行,防止程序崩溃
  • 用f"{columns[0]}.txt"把姓名作为输出文件名,让每个文件对应唯一的用户

执行后,文件会按以下结构生成:

C:/Desktop/main_folder/
├─ folder_1/
│  ├─ November/
│  │  └─ Bob.txt
│  └─ December/
│     └─ Sam.txt
├─ folder_2/
│  └─ April/
│     └─ Jane.txt
└─ folder_3/
   └─ January/
      └─ Jon.txt

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 14:40:49