Home > database >  Search for specific str in a csv file
Search for specific str in a csv file

Time:04-25

I have to create a guessing game where each user creates a library of movies and then the other person has to guess a movie title.

I save the movies into a csv file. I am trying to create a function where a user makes a guess and if the movie name is found in the csv then print "Congrats" else "guess again". I have it reading the file but it returns guess again or congrats for every field in the file. How can I just return it once? if it is in any field print congrats or if it is not in any field then guess again but all only once. I don't want to have it search by a specific row number since it could be found in any of the rows.

Here is my current function I am using where the csv file referenced is the list of movie titles of the other player.

def guessingPlayer1v3(num_guesses):
    for guess in range(0, num_guesses):
        Guess=input("Movie title guess: ") #players guess
        Guess=Guess.lower().strip() #guess to search for
        with open('collection2.csv', 'r') as f_obj:
            reader=csv.reader(f_obj, delimiter=',')
            for row in reader:
                for field in row:
                    if field == Guess:
                        print("Congrats, you guessed a title")
                    else:
                        print("Guess Again")

and it is returning:

Movie title guess: cat in the hat
Guess Again
Guess Again
Guess Again
Guess Again
Guess Again
Guess Again

Movie title guess: all dogs go to heaven
Guess Again
Guess Again
Guess Again
Congrats, you guessed a title
Guess Again
Guess Again

CodePudding user response:

You can try something like this:

import csv

listOfMovies = []

with open('collection2.csv', newline='') as f:
    reader = list(csv.reader(f))
    for line in reader:
        listOfMovies.append(line[0])

def guessingPlayer1v3(num_guesses):
    for guess in range(0, num_guesses):
        Guess=input("Movie title guess: ").lower().strip() 
        if Guess in listOfMovies:
            print("Congrats, you guessed a title")
            break
        else:
            print("Guess Again")

CodePudding user response:

There are two print statements, the first one determine if player input has correct, and the second are showing every row "Guess Again", revoming else statement and adding a return statement will avoid this, once the name has stored on a variable just iterate over all rows and compare it...

for row in reader:
    for field in row:
        if field == Guess:
            print("Congrats, you guessed a title")
            return

print("Guess Again") # if movie is not in file
  • Related