Home > Software design >  Write a new row with each column in python csv.writer
Write a new row with each column in python csv.writer

Time:04-13

I currently have a csv with the following columns:

id, width, height, item_id, design

I would like to append to this file and create a new row filling each one of those columns. When I try it with let's say "test here" it places t, e, s, t etc in each row. I would like to put data in id, width, height separte in example "new id", "new width", etc

My code so far is:

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 only accepts one argument. Any idea how I can accomplish this?

CodePudding user response:

That happens because writerow expects to receive an Iterable, like a list. Python treats strings as iterables of type char, so if you type "hello", it will be processed as ['h', 'e', 'l', 'l', 'o'].

Try using a list in the writerow function:

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