Q:

Python: Merge two csv files and mark the unmatched both in master and using data

I am a bit new to python so sorry if my question is irrelevant. I have two csv files similar to this that I want to match  
file 1 
sa_name  
ABC  
DEF  
ACE  
ABCD  
BCD    

And file 2 
rs_name  
ABCD  
CDE  
DEFG  
ABCDE  
ABE  

And I want my output file to be like this:
output file 
sa_name, rs_name, merge  
ABC, ABCD, 3  
ABC, ABCDE, 3  
ACE, ,1  
DEF, DEFG, 3  
ABCD, ABCDE, 3  
ABCD, ABCD, 3
BCD, ABCD, 3  
BCD, ABCDE, 3  
 , CDE, 2  
 , ABE, 2

So the rule is that merge=3 if row in file1.csv is a substring of a row in file2, if the data is only in file1.csv then merge=1 and if the data is only in file2.csv then merge=2.  
I only know how to get those rows with merge=3 but don't know how to merge two csv files and keep those unmatched in the output file and also indicate  whether they come from file 1 or file 2.
Here comes my code:  
import csv

with open('file2.csv', encoding='UTF-8', newline='') as RS:
RS_reader = csv.reader(RS)
rows = [row for row in RS_reader] 
print("RS data loaded...")

with open('file2.csv', encoding='UTF-8', newline='') as SA:
with open('RS_SA.csv', 'w', encoding='UTF-8') as RS_SA:
    SA_reader = csv.reader(SA)
    print("SA data loaded")
    RS_SA_writer = csv.writer(RS_SA)
    RS_SA_writer.writerow(next(SA_reader, None) + rows[0])
    print("Header written to the ourput file...")

    d = 0
    for line in SA_reader:
        match2 = line[0]
        for row in rows:
            match1 = row[0]      
            if match2 in match1:
                new_row = [','.join(line+row)] 
                SA_writer.writerow(new_row)
                d = d+1
                print(d)
                print(new_row)

Anyone knows how to proceed?
Thanks a lot!  
Some updates: in my file1 I have 100 columns and 6 millions observations and file 2 I have 20 columns with 3,500 observations. Those are not relevant for my matching so I didn't add them here in the example files.

A:

Assuming you've read the two files into "sa_name" and "rs_name", this will give you a final_list which is a list of lists each one representing a row to write to a csv file. You can then sort by the first column if needed. This may need some validation depending on how big your file is etc
sa_name  = ['ABC','DEF','ACE','ABCD','BCD']
rs_name  = ['ABCD','CDE','DEFG','ABCDE','ABE']
found_rs_name, final_list = [], []

for sa in sa_name:
    found = False 
    for rs in rs_name:
        if sa in rs:
            final_list.append([sa,rs,3])
            found_rs_name.append(rs)
            found = True

    if not found:
        final_list.append([sa,"",1])

for rs in rs_name:
    if rs not in found_rs_name:
        final_list.append(["",rs,2])

