0

I wanted to search through a csv file that will look up keywords from a list within the first two columns. I've managed to get it to work when a key word is found, but wanted to have a message if no keywords found. Unfortunately the message "not found" comes out four times. I just wanted this to come out once. Please can you help? What it's doing is going around each key word again.

import csv
keywords=["none","blank","off","screen","blank"]
f=open("CSVSolutions.csv")
for row in csv.reader(f):
    for keyword in keywords:
        if keyword == row[0] or keyword == row[1]:
            print(row[2])
            break
        else:
            print ("not found")
            break
f.close
1
  • call the close method f.close -> f.close() Commented Jun 8, 2015 at 22:17

3 Answers 3

3

You can use for.. else here like so:

for keyword in keywords:
    if keyword == row[0] or keyword == row[1]:
        break
else:
    print("not found")
Sign up to request clarification or add additional context in comments.

Comments

3

Looks like you want to emit the message "Not found" only when the keywords were not found in the entire file?

try this:

import csv
keywords=["none","blank","off","screen","blank"]
f=open("CSVSolutions.csv")

for row in csv.reader(f):
    found = False;
    for keyword in keywords:
        if keyword == row[0] or keyword == row[1]:
            print(row[2])
            found = True
            break
    if not found:
        print ("not found")
        break

f.close()

The main point being that you should use another variable to track the state that you're looking for.

Comments

0
import csv
keywords=["none","blank","off","screen","blank"]

f=open("CSVSolutions.csv")
for row in csv.reader(f):
    if row[0] in keywords or row[1] in keywords:
        print(row[2])
    else:
        print ("not found")
f.close

I figured avoiding nested for entirely was easier. It may seem slower to iterate over the keywords list twice but it's basically equivalent to making two comparisons per item anyways.

3 Comments

Please add descriptions of your changes and/or code comments
Thanks for all the help, the last code prints out four outputs, which I wanted to avoid. I will try the others
Neither of the above worked unfortunately. The first one doesn't print anything when the keyword is found. The csv is very basic, you can imagine that the first two columns contain keywords, if they are matched that whatever is in column three is printed. Closess I get is Not found printing out 4 times. Can't see why that is. I've tried putting a break after the not found statement. Still no luck. But appreciate all the help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.