1.写入csv数据

#encoding:utf-8
import csv

header=['class','name','sex','height','year']

rows=[

[1,'xiaoming','male',168,23],

[1,'xiaohong','female',162,22],

[2,'xiaozhang','female',158,21],

[2,'xiaoli','male',158,21]

]

with open('csvdir.csv','w',newline='',encoding='utf-8')as f:          #newline=" "是为了避免写入之后有空行

        ff=csv.writer(f)

        ff.writerow(header)

        ff.writerows(rows)

2.在写入字典序列类型数据的时候,需要传入两个参数,一个是文件对象——f,一个是字段名称——fieldnames,到时候要写入表头的时候,只需要调用writerheader方法,写入一行字典系列数据调用writerrow方法,并传入相应字典参数,写入多行调用writerows

import csv

headers = ['class','name','sex','height','year']

rows = [

        {'class':1,'name':'xiaoming','sex':'male','height':168,'year':23},

        {'class':1,'name':'xiaohong','sex':'female','height':162,'year':22},

        {'class':2,'name':'xiaozhang','sex':'female','height':163,'year':21},

        {'class':2,'name':'xiaoli','sex':'male','height':158,'year':21},

    ]

with open('test2.csv','w',newline='',encoding='utf-8')as f:

      f_csv = csv.DictWriter(f,headers)

      f_csv.writeheader()

      f_csv.writerows(rows)

注意:列表和字典形式的数据写入是不一样的!!!!!!

3.csv的读取,和读取文件差不多:

import csv 

with open('test.csv')as f:

    f_csv = csv.reader(f)

    for row in f_csv:

        print(row)

参考:
作者:小二哥很二
链接:https://www.jianshu.com/p/ab49aecd9db2

https://www.cnblogs.com/qican/p/11122206.html

相关文章:

  • 2022-02-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-10-31
  • 2021-06-07
  • 2021-12-03
  • 2021-05-22
  • 2022-02-04
  • 2021-11-17
相关资源
相似解决方案