Den Andreychuk
Den Andreychuk

Reputation: 488

New column for each element of the array

I use the csv library to create a table of products. In order to then import it to the site, I need that each characteristic be written in a separate column.

Adding a new row is done using simple loop:

writer = csv.writer(csvfile)

for product in products:
    writer.writerow((product['price'],
                     product['vendor_code'],
                     product['characteristics']))

Adding a new product:

product = []
product.append({
    'price'             : price,
    'vendor_code'       : vendor_code,
    'characteristics'   : characteristics,
})

characteristics - array that contains each characteristic as a separate element

How do I get the output file in this form:

190$    #0172    characteristic1     characteristic2     characteristic3

characteristics - initialization:

try:
    characteristics = []
    soup_characteristics = soup.find_all('tr', {'class' : 'product_card__product_characters_item clearfix'})
    for ch in soup_characteristics:
        characteristics.append(re.sub('\s\s+|\n',' ', ch.text))
except AttributeError:
    characteristics = ""

Upvotes: 0

Views: 55

Answers (2)

neurite
neurite

Reputation: 2824

Try unpacking the characteristic array:

for product in products:
    writer.writerow((product['price'],
                     product['vendor_code'],
                     *product['characteristics']))

Here is the code I tested:

products = [{
    'price': 100,
    'vendor': 123,
    'characters': [7, 8, 9],
}]
with open('test.csv', 'w') as fo:
    writer = csv.writer(fo)
    for p in products:
        writer.writerow((
            p['price'],
            p['vendor'],
            *p['characters'],
        ))

Here is the content of the test.csv file:

100,123,7,8,9

Upvotes: 1

17slim
17slim

Reputation: 1243

You should be able to build a list to write as an entire row:

for product in products:
    row = [product['price'],product['vendor_code']] # [price,vendor_code]
    row.extend(product['characteristics']) # [price,vendor_code,characteristic1,characteristic2,...]
    writer.writerow(row) # writes each value in the list as a new column

Upvotes: 0

Related Questions