How to search CSV line for string in certain column, print entire line to file if found
<p>Sorry, very much a beginner with Python and could really use some help.</p>

<p>I have a large CSV file, items separated by commas, that I'm trying to go through with Python. Here is an example of a line in the CSV.</p>

<p>123123,JOHN SMITH,SMITH FARMS,A,N,N,12345 123 AVE,CITY,NE,68355,US,12345 123 AVE,CITY,NE,68355,US,(123) 555-5555,(321) 555-5555,JSMITH@HOTMAIL.COM,15-JUL-16,11111,2013,22-DEC-93,NE,2,1\par</p>

<p>I'd like my code to scan each line and look at only the 9th item (the state). For every item that matches my query, I'd like that entire line to be written to an CSV.</p>

<p>The problem I have is that my code will find <em>every</em> occurrence of my query throughout the entire line, instead of just the 9th item. For example, if I scan looking for "NE", it will write the above line in my CSV, but also one that contains the string "NEARY ROAD."</p>

<p>Sorry if my terminology is off, again, I'm a beginner. Any help would be greatly appreciated.</p>

<p>I've listed my coding below:</p>

<pre><code>import csv

with open('Sample.csv', 'rb') as f, open('NE_Sample.csv', 'wb') as outf:
    reader = csv.reader(f, delimiter=',')
    writer = csv.writer(outf)
    for line in f:
        if "NE" in line:
             print ('Found: []'.format(line))
             writer.writerow([line])
</code></pre>

<p>You're not actually using your <code>reader</code> to read the input CSV, you're just reading the raw lines from the file itself.</p>

<p>A fixed version looks like the following (untested):</p>

<pre><code>import csv

with open('Sample.csv', 'rb') as f, open('NE_Sample.csv', 'wb') as outf:
    reader = csv.reader(f, delimiter=',')
    writer = csv.writer(outf)
    for row in reader:
        if row[8] == 'NE':
             print ('Found: {}'.format(row))
             writer.writerow(row)
</code></pre>

<p>The changes are as follows:</p>

<ul>
<li>Instead of iterating over the input file's lines, we iterate over the rows parsed by the <code>reader</code> (each of which is a <code>list</code> of each of the values in the row).</li>
<li>We check to see if the 9th item in the row (i.e. <code>row[8]</code>) is equal to <code>"NE"</code>.</li>
<li>If so, we output that row to the output file by passing it in, as-is, to the writer's <code>writerow</code> method.</li>
<li>I also fixed a typo in your <code>print</code> statement - the <code>format</code> method uses braces (not square brackets) to mark replacement locations.</li>
</ul>

python string csv search