在csv文件中写行号 [英] Write row numbers in csv file

查看:187
本文介绍了在csv文件中写行号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在csv文件(1,2,3 ......)的A列中写行号,但我没有在csv文档中看到过这样做的功能。我的代码中的循环不正确,因为行号没有累积(停留1)。



我尝试过:



I would like to write row numbers in column A in csv file (1, 2, 3...), but I haven't seen a function in csv documentation that does it. The loop in my code below is not correct since the row number is not accumulated (stays 1).

What I have tried:

with open('file.csv', 'w', newline='') as f:
w = csv.writer(f, delimiter = ',')
i = 1
for i, row in enumerate([]):
   data = [[i, some_data]]
   w.writerows(data)
   i += 1

推荐答案

引用:

但我还没有看到一个功能在执行它的csv文档中。

but I haven't seen a function in csv documentation that does it.



正常情况下,CSV格式没有这样的概念。

最简单的解决方案是将行号视为第一行每行中的行数据,就像你的代码一样。

不要忘记添加一个字段名称id文件有一些。



您应该尝试以下方法:


Normal, there is no such concept in CSV format.
The simplest solution is to treat the row number like the first row data in each row, just like in your code.
Don't forget to add a field name id the file have some.

You should try something like:

with open('file.csv', 'w', newline='') as f:
w = csv.writer(f, delimiter = ',')
for i, row in enumerate(YourDataList):
   data = [[i, some_data]]
   w.writerows(data)



你的代码缺乏有关您数据的信息。


Your code lack information about your data.


这篇关于在csv文件中写行号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆