当前位置 : 主页 > 编程语言 > python >

爬虫学习(16):CSV文件存储

来源:互联网 收集:自由互联 发布时间:2022-06-15
写入: import csv with open ( 'data.csv' , 'w' , encoding = 'gbk' ) as f : #如果是csv一定要用gbk编译方式,utf-8乱码 writer = csv . writer ( f ) #writer方法初始化写入对象 writer . writerow ([ 'id' , 'name' , 'age' ]

写入:

import csv
with open('data.csv','w',encoding='gbk') as f: #如果是csv一定要用gbk编译方式,utf-8乱码
writer=csv.writer(f)#writer方法初始化写入对象
writer.writerow(['id','name','age'])#writerow写入每一行数据
writer.writerow(['1','川川','20'])
writer.writerow(['3','笨笨','21'])
writer.writerow(['4','憨憨','21'])

爬虫学习(16):CSV文件存储_csv

爬虫学习(16):CSV文件存储_初始化_02
去掉逗号:

import csv
with open('bb.csv','w',encoding='gbk') as f:
writer=csv.writer(f,delimiter=' ')#writer方法初始化写入对象
writer.writerow(['id','name','age'])#writerow写入每一行数据
writer.writerow(['1','川川','20'])
writer.writerow(['3','笨笨','21'])
writer.writerow(['4','憨憨','21'])

爬虫学习(16):CSV文件存储_csv_03
多行写入:

writer.writerow(['id','name','age'])
writer.writerow([['1','川川','20'],['3','笨笨','21'],['4','憨憨','21']])

字典传入CSV:

with open('bb.csv','w',encoding='gbk') as f:
filename=['id','age','interest']
writer=csv.DictWriter(f,fieldnames=filename)#初始化字典
writer.writeheader()#写入头信息
writer.writerow({'id':'1001','age':'15','interest':'play'})
writer.writerow({'id':'1002','age':'25','interest':'ll'})

如果还要追加信息,把w改成a就好了

读取csv文件:

import csv
with open('bb.csv','r',encoding='utf-8') as f:
r=csv.reader(f)
for row in r:
print(row)

主要通过遍历打印出来

或者用简单的方法pandas的read_csv

import pandas as pd
d=pd.read_csv('bb.csv')
print(d)


网友评论