I’m having a little trouble with converting a text file to a list.
the text file is presented like this:
5658845
4520125
7895122
8777541
8451277
1302850
8080152
I have written code that takes user input and tries to determine if the user input is in the list. I am however having some trouble in searching the list as I can only get a result on the last result in the list, where am I going wrong?
def accountReader():
while True:
chargeInput = (raw_input ("Enter a charge account to be validated: "))
if chargeInput == '':
break
sys.exit
else:
chargeAccount = open('charge_accounts.txt', 'r')
line = chargeAccount.readline()
while line != '':
if chargeInput == line:
print chargeInput, 'was found in list.'
else:
print chargeInput, 'not found in list.'
break
chargeFile.close
A line-by-line breakdown:
Ok, so far so good. You’ve created a loop that repeatedly asks the user for input and breaks when the user inputs nothing.
Here’s where you start running into problems.
readlinereads a single line fromchargeAccountand stores it inline. That means you can only test one line!This further compounds your problem. If
chargeInput == line, then this prints a message and then the loop repeats. Since there’s nothing to break out of the loop, this will result in an infinite loop that constantly tests one single line from the file. Also, because each line from the file ends with a newline (\n),chargeInput == linewill always yield false (thanks Steven Rumbalski for reminding me of this). Use.strip()(as suggested in matchw’s answer), or, if you can tolerate partial matches, you could use Python’s simple substring matching functionality:if chargeInput in line.And here, as sarnold pointed out, you’ve misnamed your file; furthermore, it’s in a completely different block of code, which means that you repeatedly open
chargeAccountfiles without closing any of them.As you can see from matchw’s post, there is a much simpler way to do what you’re trying to do. But I think you’d do well to figure out how to write this code correctly in the style you’ve chosen. I’ll give you one hint: there should be a
line = chargeAccount.readline()inside the innermost while loop. Do you see why? Also, you should probably exit the loop when you succeed in finding a match, not when you fail. Then you should think about a way to test whether the search was a success after the innermost loop has completed.