csv文件操作

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

效果:

csv文件操作

注意: 读取和写入都是以二进制的方式,才能保证没有空行

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

csv文件操作

但是,在python3中writerow CSV文件多一个空行,如图:

csv文件操作

解决方法:

打开文件时指定换行符为""(空字符)

#打开文件时候,指定换行符为""
with open('infos.csv','w',newline='') as f:
csvout = csv.writer(f)
csvout.writerows(infos)
上一篇:jQuery easyUI id选择器 类选择器 标签选择器 属性选择器 及DOM对象和jQuery相互之间的转换


下一篇:vue全面介绍--全家桶、项目实例