Python3使用csv模块csv.writer().writerow()保存csv文件多一行空行的问题

解决方法

file_write = open("positive_example.csv", "w",newline='')# 加上 newline 防止每行多一行空格
writer = csv.writer(file_write)
writer.writerow(fileHeader)# 写一行表头

解释

当写文件时,如果不设置newline参数,那么输入中的任何’\n’都会被翻译成当前系统的换行符line separator(也就是os.linesep);
如果参数为’‘或者’\n’,不会有任何翻译。
如果是任何其他的合法输入值,’\n’会被翻译成相应的值

When writing output to the stream, if newline is None, any ‘\n’ characters written are translated to the system default line separator, os.linesep. If newline is ‘’ or ‘\n’, no translation takes place. If newlineis any of the other legal values, any ‘\n’ characters written are translated to the given string.

ps:不同操作系统换行符不统一 linux:\n windows:\r\n mac:\r

python2.7

python 2.7 open函数中无newline参数。python 3以上版本中会有newline这个参数。

解决方法:open(‘xxx.csv’,‘w’) 改写为 open(‘xxx.csv’,‘wb’)

猜你喜欢

转载自blog.csdn.net/qq_35608277/article/details/112408609