wanlifeipeng

  博客园 :: 首页 :: 博问 :: 闪存 :: :: 联系 :: 订阅 订阅 :: 管理 ::

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)

 

posted on 2017-04-01 16:55  wanlifeipeng  阅读(259)  评论(0编辑  收藏  举报