-2
code = raw_input("Enter Code: ')
for line in open('test.txt', 'r'):
    if code in line:
        print line
    else:
        print 'Not in file'

The test.txt file looks like this

A        1234567
AB       2345678
ABC      3456789
ABC1     4567890

When input is A The print line returns all lines with A instead of just the first line. Note: the test.txt file has approximately 2000 entry's. I just want to return the line with the numbers for what ever the user inputs for now

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
  • 1
    @juanchopanza I was just DOING that :) – Adam Smith May 06 '14 at 17:08
  • OP: Your code won't currently run (your quote marks don't match). Please provide a [MCVE](http://stackoverflow.com/help/mcve) – Adam Smith May 06 '14 at 17:09
  • 1
    Well, you're using `in`, which checks if the string `"A"` is in the line. Why would you expect `"AB 2345678"` to not have `"A"` in it? It's right there. At the start. Hint: you probably want `.split()` and `==`. – Wooble May 06 '14 at 17:10

1 Answers1

1

As @Wooble points out in the comments, the problem is your use of the in operator to test for equivalency rather than membership.

code = raw_input("Enter Code: ")
for line in open('test.txt', 'r'):
    if code.upper() == line.split()[0].strip().upper():
        print line
    else:
        print 'Not in file'
        # this will print after every line, is that what you want?

That said, probably a better idea (dependent on your use case anyway) is to pull the file into a dictionary and use that instead.

def load(filename):
    fileinfo = {}
    with open(filename) as in_file:
        for line in in_file:
            key,value = map(str.strip, line.split())
            if key in fileinfo:
                # how do you want to handle duplicate keys?
            else:
                fileinfo[key] = value
    return fileinfo

Then after you load it all in:

def pick(from_dict):
    choice = raw_input("Pick a key: ")
    return from_dict.get(choice, "Not in file")

And run as:

>>> data = load("test.txt")
>>> print(pick(data))
Pick a key: A
1234567
Adam Smith
  • 52,157
  • 12
  • 73
  • 112
  • OP: you attempted to edit my post instead of writing a comment :). To get the values as an integer, just call `int` on them (e.g. in `def pick` do `return from_dict.get(int(choice), "Not in file")` – Adam Smith May 06 '14 at 18:02
  • Sorry I am first time here. and very new to python. Upon running the script it does return the value of A however the following is also on the next line. memory problem? – user3609157 May 06 '14 at 18:26
  • @user3609157 `value = int(pick(data))` will store the value as an int in the variable `value`. – Adam Smith May 06 '14 at 18:29