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

如何使用Python或Linux根据结构化TXT文件批量创建文件夹和Word文档

实现方案

方案1:Python实现(可直接对接后续Word生成逻辑,推荐)

核心逻辑就是用路径栈维护当前层级的父路径,不需要频繁切换工作目录,完全规避路径适配问题:

  • 提前约定缩进规则,比如示例中每级缩进为4个空格,计算每行的层级数
  • 维护一个列表作为路径栈,栈的长度等于当前所处的目录层级,栈中每个元素对应各级父目录的绝对路径
  • 遍历每行时先根据当前层级截断路径栈到对应长度,再拼接当前条目的路径,判断是目录还是Word文件分别处理

示例代码如下:

import os
import shutil

# 配置项
TXT_PATH = "你的输入文件路径.txt"
ROOT_DIR = "生成的根目录路径"
INDENT_PER_LEVEL = 4  # 每级缩进的空格数,若用制表符作为缩进单位则改成1
BLANK_DOCX_TEMPLATE = "blank_template.docx" # 提前准备一个空白Word文件作为模板,避免生成的空文件无法打开

path_stack = []  # 路径栈,存储各级目录的绝对路径

with open(TXT_PATH, 'r', encoding='utf-8') as f:
    for line in f:
        line = line.rstrip('\n')
        if not line.strip():  # 跳过空行
            continue
        # 计算当前行的缩进量和层级
        indent_len = len(line) - len(line.lstrip(' '))
        current_level = indent_len // INDENT_PER_LEVEL
        # 提取当前条目名称
        item_name = line.strip()
        # 截断路径栈到当前层级的父级长度
        path_stack = path_stack[:current_level]
        # 拼接当前条目完整路径
        current_full_path = os.path.join(ROOT_DIR, *path_stack, item_name)
        # 判断是目录还是Word文件:可根据自己的规则调整判断条件,示例中以Item开头的是Word文件
        if item_name.startswith("Item"):
            # 保证Word文件的父目录存在
            os.makedirs(os.path.dirname(current_full_path), exist_ok=True)
            word_path = f"{current_full_path}.docx"
            # 复制空白模板生成有效Word文件,可替换为你自己的Word生成逻辑
            shutil.copy(BLANK_DOCX_TEMPLATE, word_path)
        else:
            # 创建目录,exist_ok=True避免重复创建报错
            os.makedirs(current_full_path, exist_ok=True)
            # 把当前目录加入路径栈
            path_stack.append(item_name)

方案2:Linux Shell实现(仅需创建目录结构和空Word文件时更轻便)

直接用Shell解析缩进层级,拼接路径后批量创建:

#!/bin/bash
# 配置项
txt_path="你的输入文件路径.txt"
root_dir="生成的根目录路径"
indent_per_level=4
blank_docx_template="blank_template.docx" # 提前准备的空白Word模板路径

mkdir -p "$root_dir"
declare -a path_stack=() # 路径栈,用数组存储各级目录名

while IFS= read -r line; do
    # 跳过空行
    [ -z "$line" ] && continue
    # 计算缩进长度和当前层级
    stripped=$(echo "$line" | sed 's/^ *//')
    indent_len=$(( ${#line} - ${#stripped} ))
    current_level=$(( indent_len / indent_per_level ))
    # 截断路径栈到对应层级
    path_stack=("${path_stack[@]:0:$current_level}")
    # 生成路径
    parent_path="$root_dir/$(IFS=/; echo "${path_stack[*]}")"
    if [[ $stripped == Item* ]]; then
        # 创建Word文件
        mkdir -p "$parent_path"
        cp "$blank_docx_template" "$parent_path/$stripped.docx"
    else
        # 创建目录
        current_path="$parent_path/$stripped"
        mkdir -p "$current_path"
        path_stack+=("$stripped")
    fi
done < "$txt_path"

给脚本加执行权限chmod +x create_struct.sh后直接运行即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 18:06:06