1

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

2 Answers 2

1

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([])
Sign up to request clarification or add additional context in comments.

9 Comments

This actually adds 11 empty rows instead of 5
For my csv file, your original code adds one blank line after each line in the original file, and my code adds 5 blank lines for each line. Please show us a sample of you csv file. Perhap there is something odd in it.
Do your original csv lines happen to end with \n\n?
Added the csv file sample
When I copy your csv example to new.csv and run my code, I get 5 blank lines after each line in the output1.csv file. There must be something else happening. How are you running the code?
|
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.