第5.2章 csv文件操作

csv格式文件默认以逗号分割

处理列表数据

import csv

data = [['name','age'],['张三',4],['李四',20]]  # 第一个元素作为csv文件的标题

# 向csv文件中写数据
with open('file/csvfile.csv','w',encoding='utf-8',newline='') as f:
    writer = csv.writer(f)
    # 每次写入一行
    # for row in data:
    #     writer.writerow(row)
# 一次写入多行 writer.writerows(data) # 从csv文件读数据 with open('file/csvfile.csv','r',encoding='utf-8',newline='') as f: reader = csv.reader(f) # reader 是一个可迭代的对象 header = next(reader) # 读取一行,接下来的读取从这一行之后开始 print(header) print('------------------------') for row in reader: print(row)

 处理字典数据

import csv

# 处理字典数据
# 写文件
header = ['name','age']
data_dict = [{'name':'张三','age':20},{'age':30,'name':'李四'}] #写入的row中的数据会按照header中键的顺序写入

with open('file/csv_dict_file.csv','w',encoding='utf-8',newline='') as f:
    writer = csv.DictWriter(f,header)
    # 将标题写入csv文件
    writer.writeheader()
    # 将其他列写入csv文件
    writer.writerows(data_dict)

# 读文件
with open('file/csv_dict_file.csv','r',encoding='utf-8',newline='') as f:
    reader = csv.DictReader(f)
    for row in reader:
        print(row.get('name'))

 

posted @ 2018-05-05 15:53  白小白001  阅读(116)  评论(0编辑  收藏  举报