python3爬虫学习之数据存储CSV

关于CSV:

https://baike.baidu.com/item/CSV/10739?fr=aladdin

这里不多赘述了

所有代码基于此:

import csv

一:数据写入

1,普通写入的两种方式

单行写入

with open("student.csv" , "w" , newline="" , encoding="utf-8") as fp:
    student = csv.writer(fp)
    student.writerow(['id' , 'name' , 'class'])
    student.writerow(['001' , '张三' , '计科16'])
    student.writerow(['002' , '李四' , '电信16'])
    student.writerow(['003' , '王五' , '软工17'])

我们写入中文时一定要指定编码,并且添加

newline=""

不然会多写一行空白

多行写入,关于指定分隔符参数

with open("student_1.csv" , "w" , newline="" , encoding="utf-8") as fp:
    student = csv.writer(fp, delimiter=" ")#delimiter=" "这个参数设置列与列之间的分隔符
    student.writerow(['id' , 'name' , 'class'])
    student.writerows([
        ['001' , '张三' , '计科16'],
        ['002' , '李四' , '电信16'],
        ['003' , '王五' , '软工17']
    ])

我们可以看见,分隔符由默认的","变成了" "

2:写入为字典

with open("student_dict.csv" , "a" , newline="" , encoding="utf-8") as fp:
    fieldnames = ['id' , 'name' , 'class']
    student = csv.DictWriter(fp , fieldnames=fieldnames)
    student.writeheader()
    student.writerow(
        {
            'id' : '001',
            'name' : '张三',
            'class' : '计科16'
        }
    )
    student.writerow(
        {
            'id': '001',
            'name': '李四',
            'class': '通信16'
        }
    )
    student.writerow(
        {
            'id': '001',
            'name': '王五',
            'class': '软工17'
        }
    )

我们为了不覆盖以前的信息,可以用"a"追加的方式写入

二:读取数据

with open("student_dict.csv" , 'r' , encoding="utf-8") as fp:
    students = csv.reader(fp)
    for student in students:
        print(student)

猜你喜欢

转载自blog.csdn.net/s_kangkang_A/article/details/89106337