1
votes

There are 40 rows of data, this script only writes 1 row into CSV file.

def get_list():
global productId
askkeyword = input('please enter keyword')
data = abc.get_product_list(['productId', 'productTitle', 'salePrice', 'originalPrice', 'imageUrl'],
                                   askkeyword, pageSize='40')
for product in data['products']:
    productId = product['productId']
    productTitle = product['productTitle']
    salePrice = product['salePrice']
    originalPrice = product['originalPrice']
    imageUrl = product['imageUrl']
    with open('data.csv', 'w', newline='') as csvfile:
        fieldnames = ['productId', 'productTitle', 'salePrice', 'originalPrice', 'imageUrl']
        writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
        writer.writeheader()
        writer.writerow({'productId': productId, 'productTitle': productTitle, 'salePrice': salePrice, 'originalPrice': originalPrice, 'imageUrl': imageUrl })
1

1 Answers

0
votes

open the csv to write outside the for-loop

Ex:

def get_list():
    global productId
    askkeyword = input('please enter keyword')
    data = abc.get_product_list(['productId', 'productTitle', 'salePrice', 'originalPrice', 'imageUrl'],
                                       askkeyword, pageSize='40')
    with open('data.csv', 'w', newline='') as csvfile:
        fieldnames = ['productId', 'productTitle', 'salePrice', 'originalPrice', 'imageUrl']
        writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
        writer.writeheader()
        for product in data['products']:
            productId = product['productId']
            productTitle = product['productTitle']
            salePrice = product['salePrice']
            originalPrice = product['originalPrice']
            imageUrl = product['imageUrl']
            writer.writerow({'productId': productId, 'productTitle': productTitle, 'salePrice': salePrice, 'originalPrice': originalPrice, 'imageUrl': imageUrl })