CSV文件存储

1.写入
①写入非字典类型数据

import csv
with open(r'C:\Users\wcl\Desktop\files\1.csv','w') as csvfile:
    writer=csv.writer(csvfile)
    writer.writerow(['id','name','age'])
    writer.writerow(['10001','Mike','20'])
    writer.writerow(['10002', 'Bob', '22'])
    writer.writerow(['10003', 'Jane', '21'])
    writer.writerows([['10004','Pete','18'],['10005','Sean','19']])

CSV文件存储_第1张图片
②写入字典类型数据

import csv
with open(r'C:\Users\wcl\Desktop\files\2.csv','a') as csvfile:
    fieldnames=['id','name','age']
    writer=csv.DictWriter(csvfile,fieldnames=fieldnames)
    writer.writeheader()
    writer.writerow({'id':'10001','name':'Mike','age':20})
    writer.writerow({'id':'10002','name':'Bob','age': 21})
    writer.writerow({'id':'10003','name':'黎明','age': 22})

CSV文件存储_第2张图片
①②的写入会写入空行,解决方式

import csv
with open(r'C:\Users\wcl\Desktop\files\1.csv','w',newline='') as csvfile:
    writer=csv.writer(csvfile)
    writer.writerow(['id','name','age'])
    writer.writerow(['10001','Mike','20'])
    writer.writerow(['10002', 'Bob', '22'])
    writer.writerow(['10003', 'Jane', '21'])
    writer.writerows([['10004','Pete','18'],['10005','Sean','19']])

CSV文件存储_第3张图片
2.读取

import csv
with open(r'C:\Users\wcl\Desktop\files\1.csv','r',encoding='utf-8') as csvfile:
    reader=csv.reader(csvfile)
    for row in reader:
        print(row)

3.利用pandas

import pandas as pd
data=[{'id':'1','name':'Bob'},{'id':'2','name':'sean'}]
data=pd.DataFrame(data)
data.to_csv(r'C:\Users\wcl\Desktop\files\4.csv')

在这里插入图片描述

你可能感兴趣的:(爬虫)