zoukankan      html  css  js  c++  java
  • python—CSV的读写

    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

    [Haima的博客] http://www.cnblogs.com/haima/
  • 相关阅读:
    线程同步锁的使用方式
    EventBus简单封装
    Dagger2不自动生成daggerXXXcomponent
    android mvp模式
    第八天
    单词统计续
    学习进度第十一周
    第七天
    第六天
    第五天
  • 原文地址:https://www.cnblogs.com/haima/p/15534685.html
Copyright © 2011-2022 走看看