3

I'm trying to create a list of rows that doesn't include 3 specific words.

word_list = ['Banned', 'On_Hold', 'Reviewing']
unknown_row = []

with open('UserFile.csv', newline='') as csvfile:
    user_reader = csv.reader(csvfile, delimiter='\t')
    for row in user_reader:
        joined = ','.join(row)
        for i in word_list:
            if i in joined:
                pass
            else:
                unknown_row.append(joined)

with open('unkown.csv', 'w', newline='') as output:
    writer = csv.writer(output, delimiter=',')
    writer.writerows(x.split(',') for x in unknown_row)

Here's the thing, if only one word is included in the word_list, then it works. But if I include two or more words, then it doesn't.

Any ideas?

Thank you

Blinhawk
  • 379
  • 2
  • 7
  • 19

1 Answers1

3

The issue with your code is here:

for i in word_list:
    if i in joined:
        pass
    else:
        unknown_row.append(joined)

Right now, if a word from word_list is not found in joined, it will continue the loop, so it will still add the row unless all the words from word_list are found in the row (This wouldn't prevent your code from working with a single "bad word", which you experienced). Instead, you want to short-circuit the loop to break if any word from word_list is found in the row.

You can make use of any here:

if not any(i in joined for i in word_list):
    unknown_row.append(joined)

This way, if a single word from word_list is found in joined, the row will not be added.

user3483203
  • 50,081
  • 9
  • 65
  • 94