I am trying to write a function in Python 3 that will write all lines that end with the string ‘halloween’ to a file. When I call this function, I can only get one line to write to the output file (file_2.txt). Can anyone point out where my problem is? Thanks in advance.
def parser(reader_o, infile_object, outfile_object):
for line in reader_o:
if line.endswith('halloween'):
return(line)
with open("file_1.txt", "r") as file_input:
reader = file_input.readlines()
with open("file_2.txt", "w") as file_output:
file_output.write(parser(reader))
This is called a generator. It can also be written as an expression instead of a function:
If you’re on Python 2.7 / 3.2, you can do the two
withs like this:You don’t need to do
readlines()on the file, just telling the loop to iterate over the open file itself will do the exact same thing.Your problem was that
returnalways would exit the loop on the first match.yieldstops the loop, passes out the value, then the generator can be started again from the same point.