foret
foret

Reputation: 347

Adding multiple empty rows to a csv file

I have a csv file with around 500 lines, i want to insert multiple empty rows for each row , i.e add 5 empty rows after each row, so i tried this

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([])

This creates 3 empty rows but not 5, i am not sure on how to add 5 rows for each row. what am i missing here

Update: CSV File sample

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

Adding the output csv file for answer code enter image description here

Upvotes: 0

Views: 2427

Answers (2)

foret
foret

Reputation: 347

The following code fixes it from the answer given by John Anderson, adding an additional newline='' parameter inside the open method gives the exact number of empty rows in range

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([])

Upvotes: 0

John Anderson
John Anderson

Reputation: 39052

Your code actually only adds one blank line. Use a loop to add as many as you want:

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([])

Upvotes: 1

Related Questions