Deleting a row if it contains a string in a CSV file
<p>I'm having trouble deleting rows in text file that contains a string in one column. My code so far is not able to delete the row, but it's able to read the text file and save it as a CSV file into separate columns. But the rows are not getting deleted.</p>

<p>This is what the values in that column looks like:</p>

<pre class="lang-none prettyprint-override"><code>Ship To or Bill To
------------------
3000000092-BILL_TO
3000000092-SHIP_TO
3000004000_SHIP_TO-INAC-EIM
</code></pre>

<p>And there are 20 more columns and 50,000k plus rows. So essentially I'm trying to delete <strong>all</strong> the rows that contain strings <code>'INAC'</code> or <code>'EIM'</code>.</p>

<pre><code>import csv

my_file_name = "NVG.txt"
cleaned_file = "cleanNVG.csv"
remove_words = ['INAC','EIM']

with open(my_file_name, 'r', newline='') as infile, \
     open(cleaned_file, 'w',newline='') as outfile:
    writer = csv.writer(outfile)
    for line in csv.reader(infile, delimiter='|'):
        if not any(remove_word in line for remove_word in remove_words):
            writer.writerow(line)
</code></pre>

<p>As other answers have pointed out, the reason your code doesn't work is because each <code>line in csv.reader</code> is actually a list of column values, so the <code>remove_word in line</code> checks to see if any of them is exactly equal to one of the <code>remove_words</code> â which is apparently never <code>True</code>.</p>

<p>If you only need to check for the words in one column there's no reason to check all of them. The following will only check one column's value and so should be significantly faster than checking all 20 or more of them in every row of your file.</p>

<pre><code>import csv

my_file_name = "NVG.txt"
cleaned_file_name = "cleanNVG.csv"
ONE_COLUMN = 1
remove_words = ['INAC', 'EIM']

with open(my_file_name, 'r', newline='') as infile, \
     open(cleaned_file_name, 'w',newline='') as outfile:
    writer = csv.writer(outfile)
    for row in csv.reader(infile, delimiter='|'):
        column = row[ONE_COLUMN]
        if not any(remove_word in column for remove_word in remove_words):
            writer.writerow(row)
</code></pre>

python python-3.x