This looks related to another question you asked (and then deleted).
I'm assuming you want to be able to read a file, create generators, combine generators, sort the output of generators, then write to a file.
Using yield
to form your generator makes life a lot easier.
Keep in mind, to sort every line like this, you will have to store it in memory. If dealing with very large files, you will need to handle this in a more memory-conscious way.
First, let's make your generator that opens a file and reads line-by-line:
def line_gen(file_name):
with open(file_name, 'r') as f:
for line in f.readlines():
yield line
Then let's "merge" the generators, by creating a generator which will iterate through each one in order.
def merge_gens(*gens):
for gen in gens:
for x in gen:
yield x
Then we can create our generators:
gen1 = line_gen('f1.txt')
gen2 = line_gen('f2.txt')
Combine them:
comb_gen = merge_gens(gen1, gen2)
Create a list from the generator. (This is the potentially-memory-intensive step.):
itered_list = [x for x in comb_gen]
Sort the list:
sorted_list = sorted(itered_list)
Write to the file:
with open('f3.txt', 'w') as f:
for line in sorted_list:
f.write(line + '\n')