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, Python2
and Python3
have different solutions.
Python2 solution:
Inside open () the mode
parameter is set wb
, this is a binary write, if you want to append to use ab
, that is Python2
written 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表格