写一个名为 members.csv 的 CSV 文件,包含客户的 ID、姓名、年龄和会员等级 (金, 银, 钻石)。请编写 Python 代码筛选出所有 金会员的信息,并将结果保存 到新的CSV文件gold_members.csv中。
import csv
header = ["id", "姓名", "年龄", "等级"]
data = [
{"id": "1", "姓名": "张三", "年龄": "15", "等级": "金"},
{"id": "2", "姓名": "李四", "年龄": "12", "等级": "银"},
{"id": "3", "姓名": "王二", "年龄": "25", "等级": "金"},
{"id": "4", "姓名": "王五", "年龄": "35", "等级": "钻石"}]
with open('gold.csv', 'w') as file:
writer = csv.DictWriter(file, header)
writer.writeheader()
writer.writerows(data)
with open('gold.csv', 'r') as file:
reader = csv.DictReader(file)
gold_members = []
for row in reader:
if row["等级"] == "金":
gold_members.append(row)
with open('gold_members.csv', 'w', encoding='utf-8') as f:
fildnames = ["id", "姓名", "年龄", "等级"]
writer = csv.DictWriter(f, fieldnames=fildnames)
writer.writeheader() #写入表头
for row in gold_members:
writer.writerow(row) #循环出两个数据行
这段代码执行以下步骤:
1.写入gold文件
2.通过条件筛选,仅保留会员等级为'Gold'的行。
3.将筛选后的数据保存到gold_members.csv
文件中,确保会保存行索引到CSV文件中。