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

如何用Python读取CSV行:首项为对象其余为属性的处理方案

Python处理CSV数据的两种需求实现

一、将CSV数据转换为指定JSON格式

用Python内置的csv和json模块就能完成转换,步骤清晰直接:

  1. 读取CSV文件的每一行数据
  2. 清理每行的无效空格与空元素,拆分出核心对象名和对应的标签列表
  3. 构建目标字典结构,最终转为JSON格式输出或保存

代码示例:

import csv
import json

# 初始化存储结果的字典
result_dict = {}

# 读取目标CSV文件(替换为你的文件名)
with open('objects.csv', 'r', encoding='utf-8') as csv_file:
    csv_reader = csv.reader(csv_file)
    for row in csv_reader:
        # 清理行内元素的前后空格,过滤空元素
        cleaned_row = [item.strip() for item in row if item.strip()]
        if not cleaned_row:
            continue
        # 提取核心对象名和标签列表
        obj_name = cleaned_row[0]
        tags_list = cleaned_row[1:]
        # 写入结果字典
        result_dict[obj_name] = {"tags": tags_list}

# 打印格式化后的JSON字符串
print(json.dumps(result_dict, indent=4))

# 也可以直接保存为JSON文件
with open('objects_tags.json', 'w', encoding='utf-8') as json_file:
    json.dump(result_dict, json_file, indent=4)

示例行Otter, web, prd, x86会被转换为:

{
    "Otter": {
        "tags": [
            "web",
            "prd",
            "x86"
        ]
    }
}

二、遍历属性并调用API完成更新

先实现CSV读取逻辑,再逐个遍历标签调用API。这里用requests库处理API请求,你需要提前通过pip install requests安装:

代码示例:

import csv
import requests

# 替换为你的实际API调用逻辑,包括地址、参数、认证等
def update_tag_via_api(obj_name, tag):
    api_url = "https://your-api-domain.com/update-tag"
    request_payload = {
        "object": obj_name,
        "tag": tag
    }
    try:
        # 根据API要求调整请求方法(POST/PUT等)
        response = requests.post(api_url, json=request_payload)
        response.raise_for_status()  # 捕获HTTP状态码错误
        print(f"{obj_name} 的标签 {tag} 更新成功")
        return response.json()
    except requests.exceptions.RequestException as e:
        print(f"{obj_name} 的标签 {tag} 更新失败: {str(e)}")
        return None

# 读取CSV并处理每个标签
with open('objects.csv', 'r', encoding='utf-8') as csv_file:
    csv_reader = csv.reader(csv_file)
    for row in csv_reader:
        cleaned_row = [item.strip() for item in row if item.strip()]
        if not cleaned_row:
            continue
        obj_name = cleaned_row[0]
        tags_list = cleaned_row[1:]
        # 逐个标签调用API
        for tag in tags_list:
            update_tag_via_api(obj_name, tag)

额外提示

  • 处理CSV时一定要清理空行和元素空格,避免传入无效数据到API
  • 根据实际API要求调整请求方法、参数格式和认证方式(比如添加headers里的token)
  • 可以增加重试机制(比如用tenacity库)来处理网络波动导致的临时失败

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 06:25:24