zoukankan      html  css  js  c++  java
  • Python_csv电子表格

     1 import csv
     2 with open('test.csv','w',newline='')as fp:
     3     test_writer=csv.writer(fp,delimiter=' ',quotechar='"')   #创建writer对象
     4     test_writer.writerow(['red','blue','green'])  #写入一行内容
     5     test_writer.writerow(['test_string']*5)
     6 
     7 with open('test.csv',newline='')as fp:
     8     test_reader=csv.reader(fp,delimiter=' ',quotechar='"')  #创建reader对象
     9     for row in test_reader: #遍历所有行
    10         print(row)  #每行作为一个列表返回
    11         # ['red', 'blue', 'green']
    12         # ['test_string', 'test_string', 'test_string', 'test_string', 'test_string']
    13 
    14 with open('test.csv',newline='')as fp:
    15     test_reader=csv.reader(fp,delimiter=':',quotechar='"')  #使用不同的分隔符
    16     for row in test_reader:
    17         print(row)  #与上面的输出不同
    18         # ['red blue green']
    19         # ['test_string test_string test_string test_string test_string']
    20 
    21 with open('test.csv',newline='')as fp:
    22     test_reader=csv.reader(fp,delimiter=' ',quotechar='"')
    23     for row in test_reader:
    24         print(','.join(row))    #重新组织数据形式
    25         # red, blue, green
    26         # test_string, test_string, test_string, test_string, test_string
    27 
    28 with open('name.csv','w')as fp:
    29     headers=['姓氏','名字']
    30     test_dictWrite=csv.DictWriter(fp,fieldnames=headers)    #创建DictWriter对象
    31     test_dictWrite.writeheader()    #写入表头信息
    32     test_dictWrite.writerow({'姓氏':'','名字':''})    #写入数据
    33     test_dictWrite.writerow({'姓氏':'','名字':'蛤蟆'})
    34     test_dictWrite.writerow({'姓氏': '', '名字': '天鹅'})
    35 
    36 with open('name.csv')as fp:
    37     test_dictReader=csv.DictReader(fp)  #创建DictReader对象
    38     print(','.join(test_dictReader.fieldnames)) #读取表头信息
    39     for row in test_dictReader:
    40         print(row['姓氏'],',',row['名字'])
    41 # 姓氏,名字
    42 # 张 , 山
    43 # 刘 , 蛤蟆
    44 # 赖 , 天鹅

    用MAC电脑内的Numbers打开name.csv文件效果图

  • 相关阅读:
    使用sublimeserver启动本地服务器进行调试
    echarts图表自适应盒子的大小(盒子的大小是动态改变的),大到需要全屏展示
    axios跨域问题
    reset.css
    Git初体验
    Window下的git配置文件在哪里【图文】
    使用better-scroll遇到的问题
    代码中特殊的注释技术 -- TODO、FIXME和XXX的用处
    vue饿了么学习笔记(1)vue-cli开启项目
    gulp4小demo
  • 原文地址:https://www.cnblogs.com/cmnz/p/6979187.html
Copyright © 2011-2022 走看看