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

时间:2018-08-30 10:29:51

标签: python python-3.x csv

我正在尝试在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

每行的相应值相同。

我缺少什么?

致谢!

1 个答案:

答案 0 :(得分: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})