Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Python data science with python 3 I have two filies. I want to match every word

ID: 3867301 • Letter: P

Question

Python data science with python 3

I have two filies. I want to match every word find in txt file 1 in txt file 2 in same order of file 1 and save that in new txt file

for example:

file 1

SN_000009.1
SN_000010.1
MP_000015.1
DB_000089.2
RN_000078.1

file2

RN_000006.1
SN_000009.1
RN_000073.1
MP_000015.1
RN_000078.1
DB_000089.2
RN_000078.1

the result file should be in same order of file 1:

SN_000009.1
MP_000015.1
DB_000089.2
RN_000078.1

my code it mtached the contents between file1 and file2 but the problem it did not make same order of file 1. it also did not match RN_000078.1


file1 = set(line.strip() for line in open('type1.txt'))

file2 = set(line.strip() for line in open('type2.txt'))


with open('some_output_file.txt', 'w') as file_out:
        for line in file1 & file2:
            if line:
                file_out.write(line)
                print (line)

Explanation / Answer

#!usr/bin/python

with open('output_file.txt','w') as file_out:
     with open("type1.txt") as file1:
          for line in file1:
              if line:
                 file2 = open("type2.txt",'r')
                 for line1 in file2:
                     if line in line1:
                       file_out.write(line)
                       print(line)
                       break