编程语言
首页 > 编程语言> > python csv 的两种创建文件和读取文件的方式

python csv 的两种创建文件和读取文件的方式

作者:互联网

import csv

# 使用列表的形式创建数据

l = [['姓名', '年龄'], ['张三', '4'], ['李四', '3']]

with open('test.csv', mode='w', encoding='utf-8-sig', newline='') as csvfile:
    writer = csv.writer(csvfile)
    for line in l:
        writer.writerow(line)


# 使用列表的形式读取数据
with open('test.csv', mode='r', encoding='utf-8-sig', newline='') as csvfile:
    reader = csv.reader(csvfile)
    print(reader)
    for i in reader:
        print(i)


# 使用字典的形式创建数据

ll = [{'姓名': '张三', '性别': '男', '年龄': '33'},
      {'姓名': '李斯', '性别': '女', '年龄': '22'},
      {'姓名': '王武', '性别': '男', '年龄': '11'}]
with open('test1.csv', mode='w', encoding='utf-8-sig', newline='') as csvfile:
    writer = csv.DictWriter(csvfile, fieldnames=ll[0].keys())
    writer.writeheader()  # 写入表头
    for _ in ll:
        writer.writerow(_)


# 使用字典的形式读取数据
with open('test1.csv', 'r', encoding='utf-8-sig', newline='') as csvfile:
    reader = csv.DictReader(csvfile)
    for _ in reader:

 

标签:文件,encoding,python,writer,csvfile,reader,csv,open
来源: https://www.cnblogs.com/amanda-yl/p/14793246.html