PythonCSV:如何使用csv模块编写多行?

2024-09-27 02:26:58 发布

您现在位置:Python中文网/ 问答频道 /正文

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

Tags: csv数据csvfiledatagetproductlistwriter
1条回答
网友
1楼 · 发布于 2024-09-27 02:26:58

打开csv以在for循环外部写入

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

相关问题 更多 >

    热门问题