python3 csv 空行解决

来源:互联网 发布:高中女神 体验知乎 编辑:程序博客网 时间:2024/06/04 15:39

python3.4遇到csv读写空行问题,在网上搜索大多数给的方案是按照二进制进行读取,python2和python3在byte和str处理不太一样,没有达到效果。

查询官方文档 csv.writer,需要加入一个newline参数读取,文档截取如下

If csvfile is a file object, it should be opened with newline=”.
footnote : If newline=” is not specified, newlines embedded inside quoted fields will not be interpreted correctly, and on platforms that use \r\n linendings on write an extra \r will be added. It should always be safe to specify newline=”, since the csv module does its own (universal) newline handling.

官方demo如下

import csvwith open('eggs.csv', 'w', newline='') as csvfile:    spamwriter = csv.writer(csvfile, delimiter=' ',                            quotechar='|', quoting=csv.QUOTE_MINIMAL)    spamwriter.writerow(['Spam'] * 5 + ['Baked Beans'])    spamwriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])

将程序改为

import csvfieldlist=[    ['one', '1'],    ['two', '2'],    ['three', '3']]with open("te_write.csv", 'w', newline='') as ff:    writer = csv.writer(ff, dialect="excel")    writer.writerows(fieldlist)

成功去除空行

0 0
原创粉丝点击