【问题标题】:How to append multiple rows to csv file using python如何使用python将多行附加到csv文件
【发布时间】:2018-05-16 00:53:12
【问题描述】:

我试图将用户输入的数据附加到行,但是我没有运气。

Counter 是一个用户定义的全局变量,我在代码的其他地方创建了它。

当附加数据时,它不会移动到另一行,而是一遍又一遍地重写同一行,作为 python 的新用户,我不知道我做错了什么。

def AppendCsv(): 
    NumberOfNamesToBeAdded()
    with open ('Graph.csv', 'a') as graphFile:
        graphFileWriter=csv.writer(graphFile)
        for x in counter:
             graphFileWriter.writerow([ID, Name,Cost,Date1]) 

【问题讨论】:

  • 什么是 ID、名称、成本和日期 1?它们会在这些循环上发生变化吗?
  • 当您说它一遍又一遍地重写同一行时,您的意思是它会覆盖同一行并且您最终只将一个新行附加到 CSV 吗?还是你的意思是同一行被追加了多次?
  • 我的意思是同一行被覆盖,所以最后只有 1 行被追加

标签: python csv append row


【解决方案1】:

一方面,这取决于counter 中的内容。在counter 中使用range,如下所示:

import csv

counter = range(3)

with open('Graph.csv', 'a', newline='') as graphFile:
    graphFileWriter = csv.writer(graphFile)
    for x in counter:
        graphFileWriter.writerow([1,2,3])

结果是这样的:

1,2,3
1,2,3
1,2,3

您可能还想在open 语句中插入, newline=''

【讨论】:

  • counter 是一个字符串,所以如果我将其更改为 counter=range(input('enter the number')) 这应该可以吗?
  • 我希望如此,是的。
猜你喜欢
  • 2014-01-27
  • 2018-05-24
  • 2013-11-03
  • 2017-07-28
  • 2019-03-26
  • 1970-01-01
  • 2022-10-25
  • 2016-03-12
  • 1970-01-01
相关资源
最近更新 更多