Issue trying to read spreadsheet line by line and write to excel (downsample)
<p>I am trying to write some code to downsample a very large excel file. It needs to copy the first 4 lines exactly, then on the 5th line start taking every 40th line. I currently have this</p>

<pre><code>import os
import string
import shutil
import datetime

folders = os.listdir('./')
names = [s for s in folders if "csv" in s]
zips = [s for s in folders if "zip" in s]
for folder in names:
    filename = folder
    shutil.move(folder, './Archive')
    with open(filename) as f:
        counter = 0
        for line in f:
            counter += 1
            f_out = open('./DownSampled/' + folder +  '.csv', 'w')
            if counter &lt; 5:
                f_out.write(line)
            elif (counter+35) % 40 == 0:
                f_out.write(line)
            f_out.close()
</code></pre>

<p>It moves the files to the Archive folder, but does not create a downsampled version, any ideas on what I could be doing wrong here?</p>

<p>You're overwriting the file on each iteration of the previous file. Move that <code>open(...)</code> out of the <code>for</code> loop:</p>

<pre><code>with open(filename) as f, open('./DownSampled/' + folder +  '.csv', 'w') as f_out:
     for i, line in enumerate(f):
         if i &lt; 5:
             f_out.write(line)
         elif (i+35) % 40 == 0:
             f_out.write(line)
</code></pre>

<p>More so, <a href="https://docs.python.org/2/library/functions.html#enumerate" rel="nofollow"><code>enumerate</code></a> can replace your count logic.</p>

python excel