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

Python遍历JIRA多项目存CSV问题:仅最后一个项目数据被保存

问题分析与解决方案

嘿,我一眼就看出问题出在哪了——你的代码每次循环处理项目时,都在重置数据容器,还覆盖了同一个CSV文件,最后当然只剩最后一个项目的数据啦!

具体问题点:

  • 你在for project in projects:循环内部定义了result = [],这意味着每处理一个新项目,之前收集的所有数据都会被清空,最后result里只装着最后一个项目的issue数据。
  • 每次循环都执行df.to_csv('/Desktop/file.csv'),默认写入模式是w(覆盖写入),所以前几个项目的数据刚写入就被后面的覆盖了。
  • 原代码还有个小bug:循环for value in issues:里,你后面用了i.timeSpentSeconds这类变量,但根本没定义i,应该用循环变量value或者把变量名改成i。

修复方案(两种可选)

方案1:先收集所有项目数据,最后一次性写入CSV

这种方式更高效,适合数据量不是特别大的场景:

import pandas as pd

projects = ['project_a','project_b']
# 把result定义在循环外面,避免每次清空
result = []

for project in projects:
    issues = jira.search_issues('project= ' + project)
    for i in issues:
        timeSpentSeconds = i.timeSpentSeconds
        timeSpent = i.timeSpent
        updated = i.updated
        started = i.started
        author = i.author
        dict_ = {
            'project': project,  # 建议加上项目名,方便区分不同项目的数据
            'value': i, 
            'timeSpent': timeSpent, 
            'updated': updated, 
            'started': started, 
            'author': author
        }
        result.append(dict_)

# 所有项目数据收集完成后,统一写入CSV
df = pd.DataFrame(result)
df.to_csv('/Desktop/file.csv', index=False)

方案2:每次循环追加数据到CSV(适合大数据量,减少内存占用)

如果项目数据量很大,不想一次性把所有数据放在内存里,可以用追加模式,注意第一次写入时保留表头,之后追加时跳过表头:

import pandas as pd

projects = ['project_a','project_b']
file_path = '/Desktop/file.csv'
# 标记是否是第一次写入,用来控制表头显示
first_write = True

for project in projects:
    issues = jira.search_issues('project= ' + project)
    result = []
    for i in issues:
        timeSpentSeconds = i.timeSpentSeconds
        timeSpent = i.timeSpent
        updated = i.updated
        started = i.started
        author = i.author
        dict_ = {
            'project': project,
            'value': i, 
            'timeSpent': timeSpent, 
            'updated': updated, 
            'started': started, 
            'author': author
        }
        result.append(dict_)
    
    df = pd.DataFrame(result)
    # 第一次写入带表头,后续追加不带表头
    if first_write:
        df.to_csv(file_path, index=False)
        first_write = False
    else:
        df.to_csv(file_path, mode='a', header=False, index=False)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 08:27:03