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文件效果图

  • 相关阅读:
    USACO Milk2 区间合并
    Codeforces 490B Queue【模拟】
    HDU 3974 Assign the task 简单搜索
    HDU 5119 Happy Matt Friends(2014北京区域赛现场赛H题 裸背包DP)
    Cin、Cout 加快效率方法
    POJ 1159 回文LCS滚动数组优化
    POJ 2479 不相交最大子段和
    POJ 1458 最长公共子序列 LCS
    在阿里最深刻的,还是职场之道给我的震撼
    精细化
  • 原文地址:https://www.cnblogs.com/cmnz/p/6979187.html
Copyright © 2011-2022 走看看