user3052940
user3052940

Reputation: 15

compare two text files in python

I'm trying to compare to text files and output the same in third one , but it does not work the two files have six rows ,the first one is like this

name 50 60 77 88
name 33 55 76 45
name 22 43 65 87
name 44 65 87 90
name 54 07 67 08

the second is like

name 77 32.88
name 86  66.9
name 55  34.8
name 34  88.9
name 42  77.6
name 22  65.9

i want to match the names to get the other information

here is what I did

file1 = open("file1.txt", "r")
file2 = open("file2.txt", "r")
file3 = open("resultss.txt", "w")
list1 = file1.readlines()
list2 = file2.readlines()
file3.write("here: \n")
for i in list1:
    for j in list2:
        if  i==j:
            file3.write(i)

Upvotes: 2

Views: 11252

Answers (3)

Totem
Totem

Reputation: 7349

Like others said, you should close your files after using them, it's good practice:

with open("filepath/file.txt", "r") as file1:
    some code here...

this automatically closes the file for you when the 'some code here' bit is done..

Here's one way to get the names and info out of the files.. using the re module(regular expressions)

t1 = [i.split() for i in list1] #test this out in the interpreter if you don't know
t2 = [i.split() for i in list2] #what it does

r = []
for i in t1:
    for j in t2:
        if i[0] == j[0]:
        r.append('name: %s - grades: %s %s' % (i[0], ' '.join(i[1:]), ' '.join(j[1:])))

This will produce output like:

['name: nameb - grades: 50 60 77 88 34 88.9',
 'name: namek - grades: 33 55 76 45 22 65.9', 
 'name: namem - grades: 22 43 65 87 42 77.6', 
 'name: Garry - grades: 44 65 87 90 86 66.9', 
 'name: Brian - grades: 54 07 67 08 77 32.88']

You could obviously format it differently

The full function:

def compare_files():

    files = ["file1", "file2"]
    file_list = []

    for file in files:
        with open("filepath/%s.txt", % file "r") as f:
            file_list.append(f.readlines())

    text1 = [i.split() for i in file_list[0]]
    text2 = [i.split() for i in file_list[1]]

    r = []
    for i in text1:
        for j in text2:
            if i[0] == j[0]:
            r.append('name: %s - grades: %s %s' % (i[0], ' '.join(i[1:]), ' '.join(j[1:])))
    #if file f3 doesn't exist this will create it
    with open("filepath/file3.txt", "w") as f3:
        for line in r:
            f3.write(i + '\n')

Upvotes: 0

Dzanvu
Dzanvu

Reputation: 523

You should close the files after you finish manipulating it. So you should add following codes to the tail of your code:

file1.close()
file2.close()
file3.close()

I hope this may help you.

Upvotes: 0

Max Noel
Max Noel

Reputation: 8910

Take a look at the difflib module in the standard library (more specifically, the difflib.unified_diff function). It does all the work for you ;)

Upvotes: 3

Related Questions