将多个空行添加到csv文件

时间:2019-01-06 16:08:38

标签: python

我有一个约有500行的csv文件,我想为每行插入多个空行,即在每行之后添加5个空行,所以我尝试了

import csv
with open("new.csv", 'r') as infile:
    read=csv.reader(infile, delimiter=',')
    with open("output1.csv", 'wt') as output:
        outwriter=csv.writer(output, delimiter=',')
        i = 0
        for row in read:
             outwriter.writerow(row)
             i += 1
             outwriter.writerow([])

这将创建3空行,但不会创建5空行,我不确定如何为每行添加5行。我在这里想念什么

更新: CSV文件示例

No,First,Sec,Thir,Fourth
1,A,B,C,D
2,A,B,C,D
3,A,B,C,D
4,A,B,C,D
5,A,B,C,D
6,A,B,C,D
7,A,B,C,D
8,A,B,C,D

添加输出的csv文件作为答案代码 enter image description here

2 个答案:

答案 0 :(得分:0)

您的代码实际上只添加了一个空白行。使用循环添加任意数量的

import csv
with open("new.csv", 'r') as infile:
    read=csv.reader(infile, delimiter=',')
    with open("output1.csv", 'wt') as output:
        outwriter=csv.writer(output, delimiter=',')
        for row in read:
             outwriter.writerow(row)
             for i in range(5):
                 outwriter.writerow([])

答案 1 :(得分:0)

以下代码根据John Anderson给出的答案进行了修复,在newline=''方法内添加了一个额外的open参数,可以得出范围内空行的确切数量

import csv
with open("new.csv", 'r') as infile:
    read=csv.reader(infile, delimiter=',')
    with open("output1.csv", 'wt',newline='') as output:
        outwriter=csv.writer(output, delimiter=',')
        for row in read:
             outwriter.writerow(row)
             for i in range(5):
                 outwriter.writerow([])