You need to enable JavaScript to run this app. Python如何实现列表匹配结果按列写入CSV而非逐行写入
优惠活动
大模型
产品
解决方案
定价
更多

Python如何实现列表匹配结果按列写入CSV而非逐行写入

代码修改方案

核心改动点

  • 调整表头结构:第一列为文件名,后续列顺序和parm_list中的参数顺序一一对应
  • 每个TXT文件处理前先初始化占位结果列表,匹配到对应参数后填充到列表的对应位置,避免匹配一个就写一行
  • 优化CSV写入逻辑,减少不必要的IO操作
  • 补充路径拼接逻辑,避免非当前目录下读取文件报错

修改后完整代码

import os
import csv
import re

# 配置项
parm_list = ["electricalAntennaTilt ","iuantSectorId ", "eUtranCellFDDId "]
directory = "./"  # 替换为你的TXT文件实际存储目录

# 删除旧结果文件
if os.path.exists("Parm.csv"):
    os.remove("Parm.csv")

# 写入表头:第一列为文件名,后续列对应parm_list的每个参数
header = ["文件名"] + parm_list
with open('Parm.csv', 'w', newline='', encoding='utf-8') as csvfile:
    writer = csv.writer(csvfile)
    writer.writerow(header)

# 遍历目录下所有文件
for filename in os.listdir(directory):
    # 跳过非TXT文件
    if not filename.endswith(".txt"):
        continue
    # 初始化当前文件的结果行,用空值占位
    row_data = [filename] + ['' for _ in parm_list]
    # 拼接完整文件路径
    file_path = os.path.join(directory, filename)
    with open(file_path, "r", encoding="UTF-8") as f:
        content = f.read()
        # 按顺序匹配每个参数
        for idx, keyword in enumerate(parm_list):
            # 匹配关键词所在的整行内容
            match_res = re.search(keyword + r'.*', content)
            if match_res:
                # 去除首尾空白后填入对应列位置
                row_data[idx+1] = match_res.group().strip()
    # 当前TXT所有参数匹配完成,一次性写入一行到CSV
    with open('Parm.csv', 'a', newline='', encoding='utf-8') as csvfile:
        writer = csv.writer(csvfile)
        writer.writerow(row_data)

补充说明

如果单个参数在同一个TXT文件中匹配到多行,可将re.search替换为re.findall,把所有匹配结果用分号等分隔符拼接后再填入对应列即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 11:51:00