1.python2中:
import csv infos = [
['peter','male'],
['marry','female'],
['johon','male'],
['rose','female'],
['mike','male']
]
#写入
with open('infos.csv','wb') as f:
csvout = csv.writer(f)
csvout.writerows(infos)
#读取
with open('infos.csv','rb') as f:
csvin = csv.reader(f)
data = [row for row in csvin]
with open('infos.csv','r') as f:
csvin = csv.reader(f)
for row in csvin:
print 'name:%s,gender:%s' %(row[0],row[1])
效果:
注意: 读取和写入都是以二进制的方式,才能保证没有空行
with open('infos.csv','wb') as f:
csvout = csv.DictWriter(f,fieldnames=['name','gender'])
csvout.writeheader()
csvout.writerows(infos) with open('infos.csv','rb') as f:
csvin = csv.DictReader(f)
data = [row for row in csvin] with open('infos.csv','r') as f:
csvin = csv.DictReader(f,fieldnames=['name','gender'])
for row in csvin:
print 'name:%s,gneder:%s' %(row['name'],row['gender'])
但是,在python3中writerow CSV文件多一个空行,如图:
解决方法:
打开文件时指定换行符为""(空字符)
#打开文件时候,指定换行符为""
with open('infos.csv','w',newline='') as f:
csvout = csv.writer(f)
csvout.writerows(infos)