欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

python存入csv

程序员文章站 2023-11-28 13:38:34
如题,后续继续优化 ......

如题,后续继续优化

import csv
# 构建表头
headers = ["id", "user_name", "age", "country"]
# 内容列表
rows = [
    ("001", "dana", 18, "china"),
    ("002", "tom", 22, "arimecan"),
    ("003", "jack", 45, "hk")
]

# 新建csv文档,默认是自动换行的,所以要 newline=""
with open("csv01.csv", "w", newline='') as f:
    f_csv=csv.writer(f)
    f_csv.writerow(headers)
    # 由于 rows是集合,需要遍历写入每一行,不然就堆在单元格
    for row in rows:
        f_csv.writerow(row)

print("finsh")