解决csv.writer写入文件有多余的空行问题
作者:灰太狼_1991 时间:2022-12-05 06:54:28
在用csv.writer写入文件的时候发现中间有多余的空行。
最早打开方式只是‘w',会出现多余的空行,网上建议使用binary形式‘wb'打开可以解决问题:
with open('egg2.csv', 'wb') as cf:
不过只能在python2下运行,python3报错:
TypeError: a bytes-like object is required, not 'str'
有人建议用encode(‘utf-8')编码转变格式,但是觉得还是比较繁琐,因为list也不支持直接的编码。
再找了一圈,找到的最佳解释:
python2.x中写入CSV时,CSV文件的创建必须加上'b'参数,即csv.writer(open('test.csv','wb')),不然会出现隔行的现象。网上搜到的解释是:python正常写入文件的时候,每行的结束默认添加'n',即0x0D,而writerow命令的结束会再增加一个0x0D0A,因此对于windows系统来说,就是两行,而采用' b'参数,用二进制进行文件写入,系统默认是不添加0x0D的。
而python3.x中换成采用newline=''这一参数来达到这一目的。
这里python2和3的问题和解决方法都给出了。
最后
python3下的正确代码:
with open('egg2.csv', 'w', newline='') as cf:
来源:https://blog.csdn.net/huitailang1991/article/details/54946528
标签:csv,writer,空行
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python网络爬虫之爬取微博热搜
2021-08-31 02:53:50
![](https://img.aspxhome.com/file/2023/8/105068_0s.jpg)
JS数组合并push与concat区别分析
2024-04-22 22:40:09
python机器学习理论与实战(二)决策树
2021-09-24 06:20:33
![](https://img.aspxhome.com/file/2023/8/110048_0s.jpg)
在ASP中使用SQL语句之5:开始执行
2007-08-11 12:36:00
基于javascript实现全国省市二级联动下拉选择菜单
2023-09-14 06:08:52
![](https://img.aspxhome.com/file/2023/3/56303_0s.jpg)
使用Python+Flask开发博客项目并实现内网穿透
2021-11-03 14:23:37
![](https://img.aspxhome.com/file/2023/4/127084_0s.jpg)
利用Python制作一个愚人节整蛊消息框
2022-08-07 22:06:53
![](https://img.aspxhome.com/file/2023/8/70898_0s.png)
解析WordPress中函数钩子hook的作用及基本用法
2023-07-08 03:27:52
![](https://img.aspxhome.com/file/2023/2/553921_0s.png)
13个你可能未使用过的Python特性分享
2021-03-07 19:14:37
Python数据分析之pandas读取数据
2023-06-17 12:53:59
![](https://img.aspxhome.com/file/2023/4/125004_0s.png)
Python使用文件锁实现进程间同步功能【基于fcntl模块】
2022-07-04 17:45:15
CentOS 7下安装Python 3.5并与Python2.7兼容并存详解
2021-09-18 03:03:32
![](https://img.aspxhome.com/file/2023/0/124290_0s.png)
通过python实现windows桌面截图代码实例
2023-11-19 03:46:27
PyTorch中的神经网络 Mnist 分类任务
2023-04-07 00:34:49
![](https://img.aspxhome.com/file/2023/4/101294_0s.png)
python实现简单的tcp 文件下载
2022-08-03 02:38:09
SQL Server使用T-SQL进阶之公用表表达式(CTE)
2024-01-17 22:42:32
![](https://img.aspxhome.com/file/2023/8/89698_0s.jpg)
JS实现div模块的截图并下载功能
2024-05-03 11:10:39
![](https://img.aspxhome.com/file/2023/2/132622_0s.png)
详解Pycharm出现out of memory的终极解决方法
2021-12-08 18:14:23
![](https://img.aspxhome.com/file/2023/0/112780_0s.png)
微信昵称带符号导致插入MySQL数据库时出错的解决方案
2024-01-20 23:40:20
判断浏览器是否接受 Cookie
2009-07-28 17:52:00