python csv 写入空行

在 Python 中使用 csv 模块写入空行,可以使用 writerow() 方法,将一个空元素列表作为参数传入。例如:

import csv
with open('example.csv', 'w', newline='') as csvfile:
    writer = csv.writer(csvfile)
    writer.writerow([])  #写入一个空行

另外,在使用 writerows() 方法写入多行数据时,也可以在数据列表中添加空列表来实现写入空行。

import csv
data = [['Name', 'Age'],
        ['John', '20'],
        ['Jane', '25'],
        ['Bob', '30'],
with open('example.csv', 'w', newline='') as csvfile:
    writer = csv.writer(csvfile)
    writer.writerows(data)

注意 使用 newline=''来避免在 Windows 系统中写入多余的空行

  •