解决方法
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’)
博客介绍了写文件时newline参数的作用,若不设置,输入中的’\n’会被翻译成系统换行符;参数为’‘或’\n’则无翻译;其他合法值会将’\n’翻译成相应值。还指出不同操作系统换行符不同,且Python 2.7的open函数无newline参数,给出改写为’wb’模式的解决方法。
3084

被折叠的 条评论
为什么被折叠?



