【问题标题】:issue with Looping through lists to write new rows in a csv file using python使用python循环遍历列表以在csv文件中写入新行的问题
【发布时间】:2021-07-03 18:11:29
【问题描述】:

我正在尝试将内容添加到我现有的 csv 文件中。这意味着我不想删除任何现有内容,而只想根据列表添加新行。

但是,在最终输出中,我没有看到 csv 中添加了任何新行。该变量还返回空列表值(请参阅代码行上的注释)。

这里我首先询问用户条目的数量。然后是每个条目的值(每列的每一行值)。然后我很简单地将它附加到最终列表中,即 total_number_of_rows 应该如下所示: [[x,x,x][xy,xy,xy].

在最终代码中,我尝试将两个列表中的值写入 CSV 文件,例如最终输出应如下所示:

id, name, color
oldvalue1, oldvalue2, oldvalues3  #assuming this is an already existing row in the csv file
x,x,x
xy,xy,xy


number_of_entries = int(input("how many entries will you need to enter:"))
each_new_row = []
total_number_of_rows = []
for i in range(number_of_entries):
    new_id = input("add new new_id")
    new_name = input ("add new date")
    new_color = input ("add new color")
    each_new_row.extend((new_id,new_name,new_color))
    print("each_new_row",each_new_row)
    total_number_of_rows.append(each_new_row)
    print("total number of rows", total_number_of_rows) # this is showing [[1,1,red],[2,2,blue]]
    each_new_row.clear()
print("total_number_of_rows", total_number_of_rows) ## this is showing [[],[]]


  
with open('file.csv', 'a',newline ="") as f:
      
        writer = csv.writer(f)
        writer.writerows(total_number_of_rows)
    #not seeing any new row added

【问题讨论】:

  • 我正在使用 list 方法用值填充 total_number_of_rows。不知何故,这没有通过。即使我在 each_new_row.clear() 之后添加 print("total_number_of_rows", total_number_of_rows) ,即直接在其下方,它也会显示相同的结果
  • # this is showing [[1,1,red],[2,2,blue]] 这不是真的,你应该再检查一次。也许你会注意到问题所在。
  • each_new_row.clear() 引起的问题。如果您注释掉这两个total_number_of_rows print statments 正常工作,但是您的列表没有正确分成子列表
  • 它可能会显示[[1,1,red]][[2,2,blue], [2,2,blue]],但不会显示[[1,1,red], [2,2,blue]]
  • @JD2775 正是我试图删除它,你能建议我如何解决这个问题吗?

标签: python loops csv file write


【解决方案1】:
each_new_row = []
# ...
for i in range(number_of_entries):
    # ...
    total_number_of_rows.append(each_new_row)
    # ...
    each_new_row.clear()

这会将 same 列表多次附加到total_number_of_rows。最后你清除了这个列表,这就是为什么total_number_of_rows 只包含空列表(它多次是同一个空列表)。

相反,您希望在每次迭代中创建一个 new 空列表,而不是一遍又一遍地重用同一个列表。

for i in range(number_of_entries):
    each_new_row = []      # do this
    # ...
    total_number_of_rows.append(each_new_row)
    # ...
    #each_new_row.clear()  # don't do this

【讨论】:

    猜你喜欢
    • 2021-01-22
    • 1970-01-01
    • 1970-01-01
    • 2018-02-07
    • 1970-01-01
    • 2013-04-08
    • 2022-12-12
    • 2019-12-13
    • 1970-01-01
    相关资源
    最近更新 更多