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>This snippet should solves your problem</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 "NE" in row:
            print ('Found: {}'.format(row))
            writer.writerow(row)
</code></pre>

<p><code>if "NE" in line</code> in your code is trying to find out whether <code>"NE"</code> is a substring of string <code>line</code>, which works not as intended. The <code>line</code>s are raw lines of your input file.</p>

<p>If you use <code>if "NE" in row:</code> where <code>row</code> is parsed line of your input file, you are doing exact element matching.</p>

python string csv search