How can I stop Python csv.DictWriter.writerows from adding blank lines between lines in Windows?

When I use Python csv.DictWriter.writerowson Windows, blank newlines are added between the lines. How to stop it? The code works fine on Linux.

+4
source share
1 answer
  • In Python 2: always open the file in binary mode; csv.DictWriter()writes \r\nline endings:

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

    From the csv.writer()documentation :

    If csvfile is a file object, it should be open with the 'b flag on platforms where it matters.

  • Python 3: newline='', csv.DictWriter() , :

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

    , csv.writer() :

    csvfile , newline=''

    [...]

    newline='' , , , , , \r\n linendings , \r. newline='', csv () .

+14

Source: https://habr.com/ru/post/1531418/


All Articles