python 使用csv 文件写入 出现多余空行数据解决方案

因为csv.writerow() 方法会造成读取时每条数据后多一条空数据 解决方案如下:

分为两种情况 python2 和 python3

先说python2版本

with open('xxx.csv','wb+',encoding='utf-8') as csvfile:#将写入方式改为wb+ 二进制写入

  writer = csv.writer(csvfile)#初始化操作

  writer = writerow([....])

with open('xxx.csv','r',encoding='utf-8') as csvfile:#读取

  reader = csv.reader(csvfile)

  for row in reader:

    print(row) #读取结果

 

python3版本 更改为二级制写入方式 会报错 官方推荐 newline='' 

 

with open('xxx.csv','w',newline='',encoding='utf-8') as csvfile:#增加参数 newline=''

  writer = csv.writer(csvfile)#初始化操作

  writer = writerow([....])

with open('xxx.csv','r',encoding='utf-8') as csvfile:#读取

  reader = csv.reader(csvfile)

  for row in reader:

    print(row) #读取结果

posted @ 2018-12-14 12:28  贫道从来不吃素  阅读(5843)  评论(0编辑  收藏  举报