I have a .txt file containing many customers’ details, dates of birth, and addresses. I instructed Python to access this file and ask for my input to search for particular birth years or zip codes.
I called the function inside the function so that it would ask for my input when it completes each search.
The code works on the first try
However the issue is after one search, it skips the ‘for’ loop and always returns ‘ match not found’ even when my input exists in the file
file = input("Enter file name: ")
custlist= open(file)
#define our function to search for component
def search():
searchword = input()
result = None
for line in custlist :
cust = line.rstrip()
if searchword in cust:
result = line
print(result)
if result is None :
print('match not found')
search()
search()
3
custlist
is not a list
, it’s an open file object. Open file objects are iterators, not collections; once a line is consumed, it’s gone, you can’t restart a new loop except by seeking back to the beginning.
You need to either:
- Change
custlist= open(file)
tocustlist= list(open(file))
(to cache the file lines once and reuse them, and also makecustlist
a sensible name). Note that this is a bad idea if the file may be large (because you need memory proportionate to file size) but does mean the code is likely to execute faster if the file is small enough. Or - Add
custlist.seek(0)
just before you begin iterating each time, or - Open the file within the function (with a
with
statement to ensure it’s reliably closed) so you open it once per loop without needing toseek
.
I’d also strongly recommend not making your function recursive, and just put it in an infinite loop with a conditional break
. As is, it’s inherently limited in how many times it can run (you keep building new stack frames, and Python will refuse to go deeper after 1000 frames by default).
6