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>If your CSV has meaningful headers an alternative solution to slicing your rows by indices, is to use the <code>DictReader</code> and <code>DictWriter</code> classes.</p>

<pre><code>#!/usr/bin/env python
from csv import DictReader, DictWriter

data = '''A,B,C
1,2,3
4,5,6
6,7,8'''

reader = DictReader(data.split('\n'))

# You'll need your fieldnames first in a list to ensure order
fieldnames = ['A', 'C']
# We'll also use a set for efficient lookup
fieldnames_set = set(fieldnames)

with open('outfile.csv', 'w') as outfile:
    writer = DictWriter(outfile, fieldnames)
    writer.writeheader()
    for row in reader:
        # Use a dictionary comprehension to iterate over the key, value pairs
        # discarding those pairs whose key is not in the set
        filtered_row = dict(
            (k, v) for k, v in row.iteritems() if k in fieldnames_set
        )
        writer.writerow(filtered_row)
</code></pre>

python csv