我如何阻止Python的csv.DictWriter.writerows在Windows中的行之间添加空行? [英] How can I stop Python's csv.DictWriter.writerows from adding empty lines between rows in Windows?
问题描述
当我在Windows上使用Python的 csv.DictWriter.writerows
时,在行之间添加空行。如何阻止?
-
在Python 2中:打开文件二进制模式,总是;
csv.DictWriter()
写入\r\\\
行结尾:
with open(filename,'ab')as outputfile:
writer = csv.DictWriter(outputfile,fieldnames)
csvfile 是一个文件对象,它必须在平台上用'b'标志打开,这样才有所作为。
-
在Python 3中:使用
newline =''
因此csv.DictWriter()
可以控制没有翻译的换行符:with open(filename,'a',newline ='')as outputfile:
writer = csv.DictWriter(outputfile,fieldnames)
同样,引用相关的
csv.writer()
documenation :
如果 csvfile 是一个文件对象,应该用
newline =''
如果未指定
newline =''
,则不会正确解释嵌入在引用字段中的换行符,\r\\\
linendings写入额外的
\r
将被添加。指定newline =''
应该是安全的,因为csv模块有自己的(通用)换行处理。
When I use Python's csv.DictWriter.writerows
on Windows, empty newlines are added between rows. How do I stop that? The code works fine on Linux.
In Python 2: Open the file in binary mode, always;
csv.DictWriter()
writes\r\n
line endings:with open(filename, 'ab') as outputfile: writer = csv.DictWriter(outputfile, fieldnames)
From the
csv.writer()
documentation:If csvfile is a file object, it must be opened with the ‘b’ flag on platforms where that makes a difference.
In Python 3: Open the file with
newline=''
socsv.DictWriter()
can control the newlines written without translation:with open(filename, 'a', newline='') as outputfile: writer = csv.DictWriter(outputfile, fieldnames)
Again, quoting the relevant
csv.writer()
documenation:If csvfile is a file object, it should be opened with
newline=''
[ ... ]
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 specifynewline=''
, since the csv module does its own (universal) newline handling.
这篇关于我如何阻止Python的csv.DictWriter.writerows在Windows中的行之间添加空行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!