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']])
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})
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']])
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')