Reputation:
I have a file which I have successfully being read into a list, I have a loop that reads through each line of that list looking for a variable called customerID
which is just a string of 4 numbers.
I'm trying to have the if statement print the index of the list that the customer ID
was found on, as well as the contents of that line (index).
def searchAccount(yourID):
global idLocation
global customerlist
with open("customers.txt", "r") as f:
customerlist = [line.strip() for line in f]
IDExists = False
for line in customerlist:
if yourID in line:
IDExists = True
break
else:
IDExists = False
if IDExists == True:
print(customerlist.index(yourID))
Upvotes: 0
Views: 83
Reputation: 561
Instead of using range(len(customerlist))
and then customerlist[i]
to get a line, you can use enumerate()
to get the index of a line and the line itself.
def search_account(your_id):
with open("customers.txt") as txt:
for i, line in enumerate(txt):
if your_id in line.strip():
print(i, line)
break
Upvotes: 2
Reputation: 495
How about looping with an index, and using the index to track where you found the id?
def searchAccount(yourID):
global idLocation # What's this for?
global customerlist
with open("customers.txt", "r") as f:
customerlist = [line.strip() for line in f]
index = -1
for i in range(len(customerlist)):
if yourID in customerlist[i]:
index = i
break
if index > -1:
print('Index was {}'.format(i))
print(customerlist[i])
Upvotes: 1