Ad

Writerow In Python 3 Writes Me Always A Blank Line Beetween The Origin Lines, Python2 Works Great. Why?

- 1 answer

I have trouble with my Code. in Python2 I use withopen to print something in a csv, it works great. When i Use Python 3 i have to remove the BinaryMode (wb) an then it always print a blank line beetween the correct lines. Why ?

with open('C:\\Users\\KDD1SGM\\Desktop\\example\\exportPython3.csv', mode="wb") as out: 
    writer = csv.writer(out, delimiter=";")
    writer.writerow(writeData)
    for i in range(len(newfunctions)):
        writer.writerow(newfunctions[i])

and the output is as follows:

line1: 1,2,3

line2: 4,5,6

....

when i try to remove the Binary Mode in with open (for Python3) the output csv is:

line1: 1,2,3

line2: 4,5,6

line3: ...

why is there a blank line now ? and how to remove it ?

Ad

Answer

In Python 2, if you open out with mode 'wb' then csv.writer writes \r\n into the file directly. It will write \r\r\n only if you open it in binary mode, because on Windows it will translate each \n into \r\n.

In Python 3 fortunately the syntax changed, so open out with the additional parameter newline='' instead to avoid any hassle.

Example:

with open('C:\\Users\\KDD1SGM\\Desktop\\example\\exportPython3.csv', mode="w", newline='') as out: 
    writer = csv.writer(out, delimiter=";")
    writer.writerow(writeData)
    for i in range(len(newfunctions)):
        writer.writerow(newfunctions[i])

Sources

Ad
source: stackoverflow.com
Ad