写入: 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 csvwith 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'])
去掉逗号:
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'])
多行写入:
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 csvwith 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 pdd=pd.read_csv('bb.csv')
print(d)