How can I stop Python's csv.DictWriter.writerows from adding empty lines between rows in Windows?

后端 未结 1 1814
臣服心动
臣服心动 2020-12-03 19:38

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.

相关标签:
1条回答
  • 2020-12-03 19:51
    • 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.

    0 讨论(0)
提交回复
热议问题