W
W
werastet2021-08-04 12:05:29
Python
werastet, 2021-08-04 12:05:29

How to compare two txt files line by line?

Good day guys!
How to compare two txt files line by line, that is, I took the first line from file 1 and compared it with all the lines of file 2, then with the second line as well, etc., and if there are the same values, then write them separately (both files in the array are more than 12GB
) I couldn't find the right one on the internet.
Please, help

Answer the question

In order to leave comments, you need to log in

4 answer(s)
S
Sergey Gornostaev, 2021-08-04
@werastet

from itertools import zip_longest

with open('first_file.txt') as f1, open('second_file.txt') as f2:
    for a, b in zip_longest(f1, f2):
        if a != b:
            print('Файлы не равны')
            break

L
low molecular macro, 2021-08-04
@molekulyarniy

https://stackoverflow.com/questions/19007383/compa...

H
HemulGM, 2021-08-04
@HemulGM

You read a line from one file, you read from another. You are comparing two strings. If the same - write to the third file. What's not clear?

U
U235U235, 2021-08-04
@U235U235

1. sort files:

sort first.txt -o first_sorted.txt
sort second.txt -o second_sorted.txt

2. compare the sorted files and display the lines that are in the first and second files:
comm -12 first_sorted.txt second_sorted.txt > result.txt

ps for windows there are similar utilities in gnuwin32 or cygwin

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question