美文网首页
python—CSV的读写

python—CSV的读写

作者: 小二哥很二 | 来源:发表于2019-06-10 16:41 被阅读0次

    1.写入csv数据

    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='')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='')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)

    相关文章

      网友评论

          本文标题:python—CSV的读写

          本文链接:https://www.haomeiwen.com/subject/txzzxctx.html