python3 csv模块的基本使用

1 读取csv文件 :

数据如下
python3 csv模块的基本使用_第1张图片
两种读取方式:

1 : 以返回列表的形式读取
# -*- coding:utf-8 -*-
import csv
def read_csv_demo1():
    with open("china_smoking.csv", "r") as fp:
        reader = csv.reader(fp)  # reader是一个迭代器
        next(reader)   # 如果不需要输出标题,可以next()方法,把迭代器往下挪
        for x in reader:  # 这样通过下标的方式去获取
            Location = x[1]
            smoking_yes_cancer_yes = x[2]
            print({"Location":Location,"smoking_yes_cancer_yes":smoking_yes_cancer_yes})

read_csv_demo1()
2 :以字典的形式读取(推荐使用)
def read_csv_demo2():
    with open("china_smoking.csv","r") as fp:
        # 使用DictReader创建的reader是一个字典对象,遍历后,不包含第一行数据
        reader = csv.DictReader(fp)
        for x in reader:
            value = {"Location":x["Location"],"smoking_yes_cancer_yes":"smoking_yes_cancer_yes"}
            print(value)

read_csv_demo2()

2 文件的写入:

1 以元组的方式写入
import csv

def writer_csv_demo1():
    headers = ["name","age","height"]
    values = [
        ("小王",18,178),
        ("小张",20,180),
        ("小李",17,166)
    ]
    with open("classroom.csv","w",encoding="utf-8",newline="") as fp:
        writer = csv.writer(fp)
        writer.writerow(headers)
        writer.writerows(values)

writer_csv_demo1()
2 以字典的形式写入(推荐使用)
def writer_csv_demo2():
    headers = ["name", "age", "height"]
    values = [
        {"name":"小王","age":18,"height":178},
        {"name":"小王","age":18,"height":178},
        {"name":"小王","age":18,"height":178}
    ]
    with open("classromm2.csv","w", encoding="utf-8",newline="") as fp:
        writer = csv.DictWriter(fp,headers) # 使用csv.DictWriter()方法,需传入两个个参数,第一个为对象,第二个为文件的title
        writer.writeheader()  # 使用此方法,写入表头
        writer.writerows(values)

writer_csv_demo2()

你可能感兴趣的:(python,数据存储)