zoukankan      html  css  js  c++  java
  • csv

    读取csv文件:

    import csv
    
    with open('stock.csv','r') as fp:
        reader = csv.reader(fp)
        titles = next(reader)
        for x in reader:
            print(x)

    这样操作,以后获取数据的时候,就要通过下表来获取数据。如果想要在获取数据的时候通过标题来获取。那么可以使用DictReader。示例代码如下:

    import csv
    
    with open('stock.csv','r') as fp:
        reader = csv.DictReader(fp)
        for x in reader:
            print(x['turnoverVol'])

    写入数据到csv文件:

    写入数据到csv文件,需要创建一个writer对象,主要用到两个方法。一个是writerow,这个是写入一行。一个是writerows,这个是写入多行。示例代码如下:

    import csv
    
    headers = ['name','age','classroom']
    values = [
        ('zhiliao',18,'111'),
        ('wena',20,'222'),
        ('bbc',21,'111')
    ]
    with open('test.csv','w',newline='') as fp:
        writer = csv.writer(fp)
        writer.writerow(headers)
        writer.writerows(values)

    也可以使用字典的方式把数据写入进去。这时候就需要使用DictWriter了。示例代码如下:

    import csv
    
    headers = ['name','age','classroom']
    values = [
        {"name":'wenn',"age":20,"classroom":'222'},
        {"name":'abc',"age":30,"classroom":'333'}
    ]
    with open('test.csv','w',encoding='utf-8',newline='') as fp:
        writer = csv.DictWriter(fp,headers)
        writer = csv.writeheader()
        writer.writerow({'name':'zhiliao',"age":18,"classroom":'111'})
        writer.writerows(values)
  • 相关阅读:
    洛谷 P2370 P2370 yyy2015c01的U盘
    洛谷 P1214 等差数列
    洛谷 P1483 序列变换
    洛谷 P2032 扫描
    洛谷 P2846 光开关
    洛谷 P2872 道路建设
    Codeforces Round #510 #C Array Product
    Codeforces Round #510 #B
    Codeforces Round #510 #A
    关于各种数字倍数的判断
  • 原文地址:https://www.cnblogs.com/jrb2018/p/10124399.html
Copyright © 2011-2022 走看看