Python-CSV:如何使用csv模块编写多行?

时间:2018-06-11 16:36:55

标签: python csv

有40行数据,此脚本只将1行写入CSV文件。

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 个答案:

答案 0 :(得分:0)

打开csv以写入for-loop

<强>实施例

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 })
相关问题