用 python csv.writer 中的每一列写一个新行

Write a new row with each column in python csv.writer

我目前有一个包含以下列的 csv:

id, width, height, item_id, design

我想附加到此文件并创建一个新行来填充这些列中的每一列。当我尝试说“在这里测试”时,它会在每一行中放置 t、e、s、t 等。 我想将数据放在 id、width、height 中,例如“new id”、“new width”等

到目前为止我的代码是:

import csv

with open('design_products_view.csv') as design_file, open('templates_view.csv') as templates, open('templates_view.csv', 'a') as templatesToWrite:
    designs = list(csv.reader(design_file, delimiter=','))
    template_files = list(csv.reader(templates, delimiter=','))
    containsProduct = "Circle"
    writer = csv.writer(templatesToWrite)

    for row in designs:
        if containsProduct in row[1]:
            rowValue = row[1].split("'")[0]
            for row in template_files:
                if row[1] != "width":
                    if rowValue in row[1] and row[3] == "8":
                        print(row[1])
                        writer.writerow("test here")

writerrow 只接受一个参数。知道我该怎么做吗?

发生这种情况是因为 writerow 期望接收一个 Iterable,例如 list。 Python 将 strings 视为类型 char 的迭代,因此如果您键入 "hello",它将被处理为 ['h', 'e', 'l', 'l', 'o'].

尝试在 writerow 函数中使用 list

writer.writerow([5, 60, 55, 4, 'metallic'])