关于Open函数的newline参数

酬勤酬勤

  • 前言
  • 初探
  • 破案

前言

工作的时候发现下面这段代码:

with open(outfile2, 'a+') as f:
	df.to_csv(f, sep='=', index_label=False, header=False)

然后我检查文件发现每两行数据间会有多余的空行,咋回事呢?

初探

去找了 pandaspandas.DataFrame.to_csv 的文档,发现这样一句话:

If a file object is passed it should be opened with newline=’’, disabling universal newlines.

正好我们这里传入的 f 就是一个 file object ,于是我在 open 函数里加了 newline=''

with open(outfile2, 'a+', newline='') as f:
	df.to_csv(f, sep='=', index_label=False, header=False)

再次运行发现多余的空行没了,为什么呢?

破案

百度就好了,这篇文章(里面case2的答案错了,应该是笔误)最后的部分作出了解答:

csv标准库中的writerow在写入文件时会加入’\r\n’作为换行符
当写文件时newline=None,csv先是将’a\r\nb\r\n’写入内存,再写入文件时,universal newlines mode工作,换行符’\n’被翻译为’\r\n’;
当写文件时newline=’’,程序写入’a\r\nb\r\n’;

你可能感兴趣的:(工作,学习,python)