• csv文件的读取和写入


    # -*- coding: utf-8 -*-
    
    import csv
    
    # 写入列表
    headers = ["index", "a_name", "b_name"]
    values = [[1, 'a', 'b'], [2, 'c', 'd'], [3, 'e', 'f']]
    # 1. values 可迭代,list,tuple
    # 2. 若结果中出现间隔空行,就加newline='' or 'w'-->'wb+'
    with open('listdemo.csv', 'w', newline='') as f:
        writer = csv.writer(f)
        writer.writerow(headers)
        writer.writerows(values)
    
    # 写入字典
    headers = ['class', 'name', 'sex', 'height', 'year']
    values = [{'class': 1, 'name': 'xiaoming', 'sex': 'male', 'height': 168, 'year': 23},
              {'class': 1, 'name': 'xiaohong', 'sex': 'female', 'height': 162, 'year': 22}]
    #  若结果中出现间隔空行,就加newline='' or 'w'-->'wb+'
    with open('dictdemo.csv', 'w', newline='') as f:
        f_csv = csv.DictWriter(f, headers)
        f_csv.writeheader()
        f_csv.writerows(values)
    
    # 读取
    # 按照列表形式取值
    # 使用csv库的内置方法reader, 相当于xlrd读取excel,当然更方便了
    with open("listdemo.csv", "r") as f:
        reader = csv.reader(f)     # reder是一个迭代器
        next(reader)               # 跳过表头/可选择不跳过
        for line in reader:
            print(line)
    
    # 按照字典形式取值
    with open("dictdemo.csv", "r") as f:
        reader = csv.DictReader(f)
        for line in reader:
            print(line, ' --- ', type(line))
            print({'name':line['name'], 'sex': line['sex']})
    
  • 相关阅读:
    Third practice 3
    Third practice 2
    Third practice 1
    mock模拟get和post请求
    eslint语法检测报错解决办法
    python 入门到实践第四章案例
    python 入门到实践第三章课后练习
    python 入门到实践第三章
    axios拦截器的使用
    axios的实例和模块封装
  • 原文地址:https://www.cnblogs.com/hui-code/p/14095460.html
Copyright © 2020-2023  润新知