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

使用writerow()写入数据时,如何获取已写入的行号?

获取csv writer已写入行号的解决方案

Got it, let's tackle this problem. The writerow() method from Python's csv module doesn't return the current row number (it just returns None), so we need to implement this ourselves. Here are a couple of straightforward approaches:

方法1:手动维护计数器

这是最直接的方式,自己定义一个变量追踪已写入的行数,每次调用writerow()后更新计数器即可。

示例代码:

import csv

with open('output.csv', 'w', newline='') as f:
    writer = csv.writer(f)
    # 初始化计数器:如果要把表头算入行号就从0开始,否则从-1开始
    current_row = 0
    
    # 写入表头
    writer.writerow(["Header1", "Header2"])
    current_row += 1
    print(f"已写入行号:{current_row}")  # 输出1
    
    # 写入数据行
    writer.writerow(["Foo", "Bar"])
    current_row += 1
    print(f"已写入行号:{current_row}")  # 输出2

方法2:自定义Writer类封装计数逻辑

如果需要在多个场景复用这个功能,可以继承csv.Writer,重写核心方法内置行号计数,还能让writerow()返回行号,更贴合你的需求:

import csv

class RowCountWriter(csv.Writer):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.row_count = 0  # 初始化为0,写入第一行后自动累加
    
    def writerow(self, row):
        super().writerow(row)
        self.row_count += 1
        return self.row_count  # 让writerow返回当前写入的行号
    
    def writerows(self, rows):
        super().writerows(rows)
        self.row_count += len(rows)  # 批量写入时直接累加行数

# 使用示例
with open('output.csv', 'w', newline='') as f:
    writer = RowCountWriter(f)
    
    # 写入表头,直接拿到行号
    row_num = writer.writerow(["Header1", "Header2"])
    print(f"已写入行号:{row_num}")  # 输出1
    
    # 写入数据行
    row_num = writer.writerow(["Foo", "Bar"])
    print(f"已写入行号:{row_num}")  # 输出2
    
    # 批量写入后查看总行数
    writer.writerows([["A", "B"], ["C", "D"]])
    print(f"当前总行数:{writer.row_count}")  # 输出4

小提醒

  • 行号的计数规则可以根据需求调整:比如不需要把表头算入行号,就把计数器初始值设为-1,写入表头后不更新即可。
  • 自定义类的方式还能兼容writerows()批量写入的场景,不用逐行处理,效率更高。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 10:23:30