0

I tried to print out the variable gayle and it assigns values correctly. I can't find why is my program stopping if i input non-existent ID.

    os.system("clear")
    print('\tSEARCH AND VIEW FILE\n')
    gayle=0

    file_input = input('Search ID Number: ')
    proj = io.open('all_projects.csv', 'r')        
    while True:
        data = proj.readline()
        if file_input in data:
            txt = data
            gayle += 1
            break
    proj.close()
    
    if gayle > 0:
        list2 = txt.split(",")
        i = Preview(list2)
        i.view()
        print(gayle)
        try_again('Search file again?','Invalid input.',2)
    elif (gayle == 0):
        print("Not exist")
Rain
  • 3
  • 2
  • you need to set initial value of `gayle ` to 0 somewhere – Vaibhav Vishal Mar 18 '21 at 07:14
  • yes, i forgot to include it. But it has gayle=0 – Rain Mar 18 '21 at 07:14
  • try printing gayle outside of the if condition – Vaibhav Vishal Mar 18 '21 at 07:16
  • Just clarifying, when you say your program is stopping do you mean it outputs "Not exist" and stops or does it look like your program freezes ? since you dont seem to have any check in your while true loop to break at the end of the file – Karan Shishoo Mar 18 '21 at 07:17
  • i have checked it through printing, and eventually its not stopping. it became infinite loop – Rain Mar 18 '21 at 07:21
  • https://stackoverflow.com/questions/3277503/how-to-read-a-file-line-by-line-into-a-list – Vaibhav Vishal Mar 18 '21 at 07:24
  • 1
    You mean why it is _not_ stopping? Rather than use while loop, I'd guess you want to iterate through each line by using eg. `for line in open("all_projects.csv", "r"): ...` You probably want to take a look at `csv` module too – EdvardM Mar 18 '21 at 07:32

1 Answers1

0

You need to only loop over lines in your file you can do this using the open() and readlines() functions. Change your file reading and loop to the following and it should work

proj = open('all_projects.csv', 'r')
Lines = proj.readlines()
proj.close()

for line in Lines:
    if file_input in line:
            txt = data
            gayle += 1
            break
Karan Shishoo
  • 2,402
  • 2
  • 17
  • 32