Copy number of rows for n number of times using Python and write them in other file
<p>Hi I'm writing a simple script to copy a set of rows from a <strong>csv</strong> file and paste them for N number of times in other file. </p>

<p>I'm not able to write the result into other file.</p>

<p>Please find the code below:</p>

<pre><code>import csv
for i in range(2):
    with open('C:\\Python\\CopyPaste\\result2.csv', 'r') as fp:
        data = fp.readlines()
    fp.close()

with open('C:\\Python\\CopyPaste\\mydata.csv', 'w') as mycsvfile:
    thedatawriter = csv.writer(mycsvfile)
    for row in data:
        thedatawriter.writerow(row)
</code></pre>

<p><img src="http://i.stack.imgur.com/ssulP.jpg" alt="enter image description here"></p>

<p>Assuming that the format of the input and output CSV files is the same, just read the input file into a string and then write it to an output file <code>N</code> times:</p>

<pre><code>N = 3

with open('C:\\Python\\CopyPaste\\result2.csv', 'r') as infile,\
         open('C:\\Python\\CopyPaste\\mydata.csv', 'w') as outfile:
    data = fp.read()    # read entire contents of input file into data

    for i in range(N):
        outfile.write(data)
</code></pre>

<p>The above answers the question literally, however, it will replicate the header row <code>N</code> times, probably not what you want. You can do this instead:</p>

<pre><code>import csv

N = 3

with open('C:\\Python\\CopyPaste\\result2.csv', 'r') as infile,\
         open('C:\\Python\\CopyPaste\\mydata.csv', 'w') as outfile:
    reader = csv.reader(infile)
    writer = csv.writer(outfile)
    writer.writerow(next(reader))    # reads header line and writes it to output file
    data = [row for row in reader]    # reads the rest of the input file
    for i in range(N):
        writer.writerows(data)
</code></pre>

<p>This code reads the first row from the input file as the header, and writes it <em>once</em> to the output CSV file. Then the remaining rows are read from the input file into the <code>data</code> list, and replicated <code>N</code> times in the output file.</p>

python csv