在Python上将数据写入CSV会将所有数据写入第一列

问题描述 投票:3回答:1

我正在尝试在Python3上写一个CSV,在读完documentation之后,我不明白为什么所有列名和所有值都写在excel的第一列'A'上,而不是单独列上的每个值。

我的功能是:

def write_data_to_csv(family_type, brand_name, items):
    family_path = get_path_and_create_if_not_exists(family_type)
    brand_file = family_path / (brand_name + '.csv')
    columns_headers = ['Product name', 'Normal price', 'Reduced price', 'Discount', 'Date']
    with open(brand_file, mode='a', buffering=1, encoding='utf-8', errors='strict', newline='\r', closefd=True) as file:
        writer = csv.DictWriter(file, fieldnames=columns_headers, dialect='excel')
        writer.writeheader()
        for item in items:
            product_name = item.get('name')
            normal_price = item.get('price')
            reduced_price = item.get('reduced_price')
            discount = item.get('discount')
            if reduced_price is None and discount is None:
                reduced_price = ''
                discount = ''
            actual_date = strftime("%A, %d %B %Y %H:%M:%S UTC %z", localtime())
            writer.writerow({'Product name': product_name, 'Normal price': normal_price, 'Reduced price': reduced_price,
                             'Discount': discount, 'Date': actual_date})

这将创建一个文件,每行的所有值都在第一列中,如a,b,c,d,e,f,g,而不是每列一个值。 b | c | d | e | f | G

这是一张图片:

enter image description here

我正在努力实现这一目标。列标题应为:

Product Name -> Column A
Normal Price -> Column B
Reduced Price -> Colum C
Discount -> Column D
Date -> Column E

并且每行的相应值相同。

我错过了什么?

问候!

python python-3.x csv
1个回答
0
投票

试试这个:

def write_data_to_csv(family_type, brand_name, items):
    family_path = get_path_and_create_if_not_exists(family_type)
    brand_file = family_path / (brand_name + '.csv')
    columns_headers = ['Product name', 'Normal price', 'Reduced price', 'Discount', 'Date']
    with open(brand_file, 'w',newline='') as file:
        writer = csv.writer(file, delimiter=',')
        col_names=[row[0] for row in column_headers] 
        writer.writerow(col_names)

        for item in items:
            product_name = item.get('name')
            normal_price = item.get('price')
            reduced_price = item.get('reduced_price')
            discount = item.get('discount')
            if reduced_price is None and discount is None:
                reduced_price = ''
                discount = ''
            actual_date = strftime("%A, %d %B %Y %H:%M:%S UTC %z", localtime())
            writer.writerow({'Product name': product_name, 'Normal price': normal_price, 'Reduced price': reduced_price,
                             'Discount': discount, 'Date': actual_date})
© www.soinside.com 2019 - 2024. All rights reserved.