【问题标题】:Python-CSV : How do you write multiples rows with csv module?Python-CSV:如何使用 csv 模块编写多行?
【发布时间】:2018-06-11 16:36:55
【问题描述】:

有 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 })

【问题讨论】:

    标签: python csv


    【解决方案1】:

    打开 csv 以在 for 循环外写入

    例如:

    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 })
    

    【讨论】:

      猜你喜欢
      • 2020-02-15
      • 2010-11-04
      • 2016-12-04
      • 1970-01-01
      • 2020-07-18
      • 2010-11-04
      • 2016-12-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多