2

I have this code:

b = str(raw_input('please enter a book '))
searchfile = open("txt.txt", "r")
for line in searchfile:
    if b in line:
        print line
        break
else:
    print 'Please try again'

This works for what I want to do, but I was wanting to improve on it by repeating the loop if it goes to the else statement. I have tried running it through a while loop but then it says 'line' is not defined, any help would be appreciated.

tzaman
  • 46,925
  • 11
  • 90
  • 115
toby
  • 31
  • 1
  • 1
  • 6
  • possible duplicate of [Python: read file line by line into array](http://stackoverflow.com/questions/3277503/python-read-file-line-by-line-into-array) – Celeo Apr 28 '15 at 17:30
  • Okay i thought it was something like that, thanks. Basically if a title of the book is not in the txt document i want to be able for it to repeat the question to give the user another chance to input a book title. – toby Apr 28 '15 at 17:34
  • In that case just put the whole thing in a `while` loop guarded by a `bool` variable, and when you find an instance of the book title in the loop set the variable so that you exit the loop. – malfunctioning Apr 28 '15 at 17:37
  • Yes it is spaced 4 times, but it reads through each book title printing not available for each one until it comes to the book that meets the search – toby Apr 28 '15 at 17:39
  • There is no such statement as `while line in searchfile:`, although there is `While True: for line...` – Ben Morris Apr 28 '15 at 17:41

2 Answers2

2

Assuming you want to repeat the search continually until something is found, you can just enclose the search in a while loop guarded by a flag variable:

with open("txt.txt") as searchfile:
    found = False
    while not found:
        b=str(raw_input('please enter a book '))
        if b == '':
            break  # allow the search-loop to quit on no input
        for line in searchfile:
            if b in line:
                print line
                found = True
                break
        else:
            print 'Please try again'
            searchfile.seek(0)  # reset file to the beginning for next search
tzaman
  • 46,925
  • 11
  • 90
  • 115
0

Try this:

searchfile = open("txt.txt", "r")
content = searchfile.readlines()
found = False

while not found:
    b = raw_input('Please enter a book ')
    for line in content:
        if b in line:
            print line
            found = True
            break
    else:
        print 'Please try again'

searchfile.close()

You load the content in a list and use a boolean flag to control if you already found the book in the file. When you find it, you're done and can close the file.

Amaury Medeiros
  • 2,093
  • 4
  • 26
  • 42