Is there a way to simplify this "n-way merge" in python
Question: So right now I've hardcoded 4 if/elif/else statements. There there a more
dynamic way to do this? For example if I wanted to do a 10 or eve a 40 way
merge?

    
    
    #4-way merge sort, sorted page files
    outfile="fullsorted.txt"
    of=open(outfile,"w")
    f1=open("temp0-sorted.txt","r")
    f2=open("temp1-sorted.txt","r")
    f3=open("temp2-sorted.txt","r")
    f4=open("temp3-sorted.txt","r")
    
    f1_line=f1.readline()
    f2_line=f2.readline()
    f3_line=f3.readline()
    f4_line=f4.readline()
    
    while len(f1_line)>0 and len(f2_line)>0 and len(f3_line)>0 and len(f4_line)>0:
      if f1_line < f2_line and f1_line < f3_line and f1_line < f4_line and len(f1_line)>0:
        of.write(f1_line)
        f1_line=f1.readline()
      elif f2_line < f3_line and f1_line < f4_line and len(f2_line)>0:
        of.write(f2_line)
        f2_line=f2.readline()
      elif f3_line < f4_line and len(f3_line)>0:
        of.write(f3_line)
        f3_line=f3.readline()
      else:
        of.write(f4_line)
        f4_line=f4.readline()
    
    of.close()
    


Answer: Just use
[`heapq.merge`](https://docs.python.org/3/library/heapq.html#heapq.merge):

    
    
    import heapq
    
    #4-way merge sort, sorted page files
    outfile="fullsorted.txt"
    
    with open("temp0-sorted.txt","r") as f1,\
         open("temp1-sorted.txt","r") as f2,\
         open("temp2-sorted.txt","r") as f3,\
         open("temp3-sorted.txt","r") as f4,\
         open(outfile,"w") as of:
        of.writelines(heapq.merge(f1, f2, f3, f4))
    

