zoukankan      html  css  js  c++  java
  • 爬虫16-csv用法

    1.读取

    import csv
    def read_csv_demo1():
        with open('stock.csv','r') as fp:
            # reader是一个迭代器
            reader=csv.reader(fp)
            next(reader)
            for x in reader:
                name=x[3]
                volumn=x[-1]
                print({"name":name,"volumn":volumn})
    
    def read_csv_demo2():
        with open('stock.csv', 'r') as fp:
            # 使用DictReader创建的reader对象
            # 不会包含标题那行的数据
            # reader是一个迭代器,遍历这个迭代器,返回来的是一个字典。
            reader=csv.DictReader(fp)
            for x in reader:
                print(x["secShortName"])
    if __name__ == '__main__':
        read_csv_demo2()
    

      

    2.写入

    #encoding: utf-8
    
    import csv
    
    def write_csv_demo1():
        headers = ['username', 'age', 'height']
        values = [
            ('張三', 18, 180),
            ('李四', 19, 190),
            ('王五', 20, 160)
        ]
    
        with open('classroom.csv', 'w', encoding='utf-8', newline='') as fp:
            writer = csv.writer(fp)
            writer.writerow(headers)
            writer.writerows(values)
    
    
    def write_csv_demo2():
        headers = ['username', 'age', 'height']
        values = [
            {'username':'张三','age':18,'height':180},
            {'username':'李四','age':19,'height':190},
            {'username':'王五','age':20,'height':160}
        ]
        with open('classroo1.csv','w',encoding='utf-8',newline='') as fp:
            writer = csv.DictWriter(fp,headers)
            # 写入表头数据的时候,需要调用writeheader方法
            writer.writeheader()
            writer.writerows(values)
    
    
    if __name__ == '__main__':
        write_csv_demo2()
    

      

  • 相关阅读:
    Redis-Sentinel 哨兵
    virtualenv and virtualenvwrapper
    C/C++中extern关键字详解
    C++ 中文拼音排序方法。
    vector排序
    VS2013 Ctrl+Shift+F 没反应
    PostMessage 解析
    CTextUI 文本控件 显示数字方法
    SetTimer API函数
    CEditUI 控件使用
  • 原文地址:https://www.cnblogs.com/wcyMiracle/p/12490172.html
Copyright © 2011-2022 走看看