Writing data to CSV on Python writes all data on first column

Viewed 455

I'm trying to write a CSV on Python3 and after read the documentation I don't understand why all the column names and all the values are writting on the first column 'A' of the excel, instead of each value on a separate column.

My function is:

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

This creates a file and all values of each row are in the fist column like a,b,c,d,e,f,g instead one value per column a | b | c | d | e | f | g

Here is a picture:

enter image description here

I'm trying to achieve this. The column headers should be:

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

And the same with the respective values on each row.

What I'm missing?

Regards!

1 Answers

Try this:

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