Home > Enterprise >  CSV Search | If / Else not working properly Python
CSV Search | If / Else not working properly Python

Time:12-10

Here is the csv file sample content that cotains id, name, author, subject, and pubdate..

2105001,Engineering Mechanics,Bela Imre Sandor,Engineering Mechanics,1983
2105002,Statics and Mechanics of Materials (2nd Edition),"William F. Riley, Leroy D. Sturges, Don H. Morris",Engineering Mechanics,2001
2105003,A Concise Introduction to Mechanics of Rigid Bodies,Loulin Huang,Engineering Mechanics,2011
2105004,Dynamics of Particles and Rigid Bodies,Mohammed F. Daqaq,Engineering Mechanics,2018
2105005,Engineering Sciences,Marcialito Modina Valenzona,Science,2002

Here is the code. The problem is even there are matching result, the code keeps turning to the "else" because some row doesn't match.

  1. like if the row contains the keyword = print those results and ignore those who don't matches.
  2. If nothing else match, then turn to else.
def linear_search_name():
  bookname=input("Enter Title of the Book: ")
  bookfile=csv.reader(open("books.csv", "r"))
  for row in bookfile:
    if bookname.casefold() in row[1].casefold():
     print("ID:", row[0],"\n", row[1],"\n",row[2],"\n",row[3],"\n",row[4],"\n")
    else:
      print("try again")
      linear_search_name()

Noob question, but i hope someone can help. Big thanks!!

CodePudding user response:

Code snippet should work fine for you:

import csv
def linear_search_name():
    bookname=input("Enter Title of the Book: ")
    bookfile=csv.reader(open("copilot-test/stack3.csv", "r"))
    match_flag = False
    for row in bookfile:
        if bookname.casefold() in row[1].casefold():
            print("ID:", row[0],"\n", row[1],"\n",row[2],"\n",row[3],"\n",row[4],"\n")
            match_flag = True
    else:
        if not match_flag:
            print("try again")
            linear_search_name()
    
linear_search_name()
  • Related