首页 > 编程语言 > 详细

Python csv模块读取基本操作

时间:2018-12-02 23:32:08      阅读:244      评论:0      收藏:0      [点我收藏+]

csv即逗号分隔值,可用Excel打开

1.向csv文件中写入数据

(1)列表方式的写入

import csv

with open(‘data.csv‘,‘a+‘,encoding=‘utf-8‘,newline=‘‘) as csvfile:
    writer = csv.writer(csvfile)

    # 写入一行 
    writer.writerow([‘1‘,‘2‘,‘3‘,‘4‘,‘5‘,‘5‘,‘6‘])

    # 写入多行
    writer.writerows([[0, 1, 3], [1, 2, 3], [2, 3, 4]])

 

(2)字典方式的写入

import csv
with open(‘data.csv‘,‘a+‘,encoding=‘utf-8‘,newline=‘‘) as csvfile:
    filename = [‘first_name‘,‘last_name‘]
    # 写入列标题
    writer = csv.DictWriter(csvfile,fieldnames=filename)
    writer.writeheader()
    writer.writerow({‘first_name‘:‘wl‘,‘last_name‘:‘wtx‘})
    writer.writerow({‘first_name‘: ‘Lovely‘, ‘last_name‘: ‘Spam‘})
    writer.writerow({‘first_name‘: ‘Wonderful‘, ‘last_name‘: ‘Spam‘})

 

 

2.读取csv文件中的内容

(1)列表方式的读取

import csv
with open(
‘data.csv‘,‘r‘,encoding=‘utf-8‘) as csvfile: reader = csv.reader(csvfile) for row in reader: # 读取出的内容是列表格式的 print(row,type(row),row[1])

 

(2)字典方式的读取

import csv

with open(‘data.csv‘,‘r‘,encoding=‘utf-8‘) as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        # 读取的内容是字典格式的
        print(row[‘last_name‘])

 

Python csv模块读取基本操作

原文:https://www.cnblogs.com/wl443587/p/10056083.html

踩
(0)
赞
(0)
   
举报
评论 一句话评论(0)
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!