【发布时间】:2019-02-05 06:25:29
【问题描述】:
我正在尝试在 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,而不是每列一个值 a |乙 | c | d |电子| f | g
这是一张图片:
我正在努力实现这一目标。列标题应为:
Product Name -> Column A
Normal Price -> Column B
Reduced Price -> Colum C
Discount -> Column D
Date -> Column E
并且每一行的相应值都相同。
我错过了什么?
问候!
【问题讨论】:
-
在 csv 中,默认 sep 是
,因此a,b,c,d,e,f,g被正确定义为 7 列 -
是的,但是当我用 excel 打开 csv 文件时,它的所有数据都存储在第一个 A 列中,而不是不同列中的每个值。我正在尝试将每个标题和值放在不同的列上。
-
您需要遍历行。似乎它将所有字典值折叠成一行值
-
Ups,我没有很好地解释它。我要更新说明。对不起!
标签: python python-3.x csv