我如何阻止Python的csv.DictWriter.writerows在Windows中的行之间添加空行? [英] How can I stop Python's csv.DictWriter.writerows from adding empty lines between rows in Windows?

查看:935
本文介绍了我如何阻止Python的csv.DictWriter.writerows在Windows中的行之间添加空行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在Windows上使用Python的 csv.DictWriter.writerows 时,在行之间添加空行。如何阻止?

解决方案


  • 在Python 2中:打开文件二进制模式,总是; csv.DictWriter()写入 \r\\\
    行结尾:

      with open(filename,'ab')as outputfile:
    writer = csv.DictWriter(outputfile,fieldnames)

    csv.writer()文件


    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='' so csv.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 specify newline='', since the csv module does its own (universal) newline handling.

这篇关于我如何阻止Python的csv.DictWriter.writerows在Windows中的行之间添加空行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆