Python written in CSV form solutions extra blank line appears

Question: When we write CSV table using Python will find will be more between each row of data a blank line?

Faced with this situation, Python2and Python3have different solutions.

Python2 solution:
Inside open () the modeparameter is set wb, this is a binary write, if you want to append to use ab, that is Python2written to use the binary format, so that no extra blank line.
code show as below:

# python2
import csv

with open('sample.csv', mode='wb') as wf:
    write = csv.writer(wf)
    msg = [
        ['name', 'pipixia'],
        ['id', '66']
    ]
    write.writerows(msg)  # 写入数据到CSV表格

Python3 solution:
In the open () which added newline=''so that no extra blank line.
code show as below:

# python3
import csv

with open('sample.csv', mode='w', newline='') as wf:
    write = csv.writer(wf)
    msg = [
        ['name', 'pipixia'],
        ['id', '66']
    ]
    write.writerows(msg)  # 写入数据到CSV表格
Published 27 original articles · won praise 10 · views 388

Guess you like

Origin blog.csdn.net/weixin_43750377/article/details/103855911