编写一个程序,汇总每种商品的销售总量和总金额,按编号排序后,写入CSV文件test7-10-2.csv,写入字段名依次为:编号、商品名称、总数量、总金额
时间: 2023-12-03 19:45:48 浏览: 149
以下是Python代码实现:
```python
import csv
# 读取原始数据
with open('test7-10-1.csv', 'r', newline='') as f:
reader = csv.reader(f)
next(reader) # 跳过标题行
sales = {}
for row in reader:
id = row[0]
name = row[1]
quantity = int(row[2])
price = float(row[3])
if id in sales:
sales[id]['quantity'] += quantity
sales[id]['amount'] += quantity * price
else:
sales[id] = {
'name': name,
'quantity': quantity,
'amount': quantity * price
}
# 按编号排序
sales = sorted(sales.items(), key=lambda x: x[0])
# 写入CSV文件
with open('test7-10-2.csv', 'w', newline='') as f:
writer = csv.writer(f)
writer.writerow(['编号', '商品名称', '总数量', '总金额'])
for id, data in sales:
writer.writerow([id, data['name'], data['quantity'], data['amount']])
```
说明:首先读取原始数据,使用字典 `sales` 统计每种商品的销售总量和总金额。然后按编号排序后,写入新的CSV文件。
阅读全文