3

This is my current code:

StockSearch = input("Search For Product (Name Or Code):\n")
with io.open('/home/jake/Projects/Stock','r', encoding='utf8') as f:
    for line in f:
        Read = f.readline()
        while Read!='':
            if StockSearch == Read:      
                print (Read)

I'm trying to get python to keep reading every line of the file until there are none left and match the user's input with one of the lines, if not it'll print an error code.

Thank you in advance.

Brendan Abel
  • 35,343
  • 14
  • 88
  • 118
  • 1
    You might find ur answer here: http://stackoverflow.com/questions/15599639/whats-perfect-counterpart-in-python-for-while-not-eof Possible duplicate! – Deca Jun 30 '16 at 16:20

3 Answers3

1
StockSearch = input("Search For Product (Name Or Code):\n")
found = False
with io.open('/home/jake/Projects/Stock','r', encoding='utf8') as f:
    for line in f:
        line = line.rstrip('\n')
        if StockSearch == line:      
            print(line)
            found = True
            break
if not found:
    print("Nothing found")
DAXaholic
  • 33,312
  • 6
  • 76
  • 74
1

This seems similar to a pattern I saw on a 'Pythonic' coding video by Raymond Hettinger. It's called iterating with a sentinel value.

The format goes like this:

with open('filename.txt') as f:
    blocks = []
    read_block = partial(f.read, 32)
    for block in iter(read_block, ''):
        blocks.append(block)

In your case, you would replace '' with your stop value.

Michael Molter
  • 1,296
  • 2
  • 14
  • 37
  • You would probably want `f.readline()` instead of `f.read(32)` since the user is trying to match whole lines, not 32-byte increments. You'd also have to strip the newline, so `read_block = lambda: f.readline().strip()` – Brendan Abel Jun 30 '16 at 17:00
0

You can just iterate over the open file to read line by line. If the condition is met, break out of the loop. Add an else statement at the end of the loop that prints the error message. The else block will only be executed if the entire file is read and no match is found.

search_text = input("Search For Product (Name Or Code):\n")
with io.open('/home/jake/Projects/Stock','r', encoding='utf8') as f:
    for line in f:
        if search_text == line.strip():
            print line
            break
    else:
        print 'Search text not found'
Brendan Abel
  • 35,343
  • 14
  • 88
  • 118