csv文件读写

csv文件读:

import csv
from collections import namedtuple


def read():
    with open('produ.csv', encoding='utf-8-sig') as f:
        reader = csv.reader(f)  # f句柄是可迭代对象,reader是生成的可迭代序列(csv.reader(f)列表从存储)
        headers = next(reader)  # (迭代器)迭代协议,迭代第一个reader
        print(headers)

        for row in reader:  # 则从第二行开始遍历 reader可迭代序列
            print(row)


def csv_read_by_nametuple():
    with open('produ.csv', encoding='utf-8-sig') as f:
        reader = csv.reader(f)  # f句柄是可迭代对象,reader是生成的可迭代序列(csv.reader(f)列表从存储)
        headers = next(reader)  # (迭代器)迭代协议,迭代第一个reader
        Row = namedtuple('Row', headers)  # 创建了一个类 类似于class
        for i in reader:
            row = Row(*i)  # 创建Row的实例row
            print(row)
            print(type(row))

            print('{}->{}->{}'.format(row.product, row.name, row.price))  # 对象实例化


def csv_read_by_dict():
    with open('produ.csv', encoding='utf-8-sig') as f:
        reader = csv.DictReader(f)
        headers = next(reader)  # (迭代器)迭代协议,迭代第一个reader
        print(headers)
        for i in reader:
            print(i)
            print(type(i))


if __name__ == '__main__':
    # read()
    # csv_read_by_nametuple()
    csv_read_by_dict()

csv文件写:

import csv


def csv_write():
    "写入文件"
    headers = ['编号', '课程', '讲师']
    rows = [
        (1, 'Python', 'Eason'),
        (2, 'C', 'dfe'),
        (3, 'fe', 'def')
    ]

    with open('mycorse.csv', 'w', encoding='utf-8', newline='') as f:
        writer = csv.writer(f)
        print(writer)
        print(type(writer))
        writer.writerow(headers)
        writer.writerows(rows)


def csv_write_dict():
    headers = ['ID', 'Title']
    rows = [
        {'ID': 1, 'Title': 'org'},
        {'ID': 2, 'Title': 'org'},
        {'ID': 3, 'Title': 'org'},
        {'ID': 4, 'Title': 'org'},
    ]
    with open('myco.csv', 'w', encoding='utf-8',newline='')as f:
        writer = csv.DictWriter(f, headers)
        writer.writeheader()
        writer.writerows(rows)


if __name__ == '__main__':
    # csv_write()
    csv_write_dict()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值