Python read CSV file, and write to another skipping columns
<p>I have CSV input file with 18 columns
I need to create new CSV file with all columns from input except column 4 and 5</p>

<p>My function now looks like</p>

<pre><code>def modify_csv_report(input_csv, output_csv):
    begin = 0
    end = 3

    with open(input_csv, "r") as file_in:
        with open(output_csv, "w") as file_out:
            writer = csv.writer(file_out)
            for row in csv.reader(file_in):
                writer.writerow(row[begin:end])
    return output_csv
</code></pre>

<p>So it reads and writes columns number 0 - 3, but i don't know how skip column 4,5 and continue from there</p>

<p>You can add the other part of the row using <em>slicing</em>, like you did with the first part:</p>

<pre><code>writer.writerow(row[:4] + row[6:])
</code></pre>

<p>Note that to include column 3, the stop index of the first slice should be 4. Specifying start index 0 is also usually not necessary.</p>

<p>A more general approach would employ a <em>list comprehension</em> and <a href="https://docs.python.org/2/library/functions.html#enumerate" rel="nofollow"><code>enumerate</code></a>:</p>

<pre><code>exclude = (4, 5)
writer.writerow([r for i, r in enumerate(row) if i not in exclude])
</code></pre>

python csv