Python 逐行比较两个大文件

Python 逐行比较两个大文件,python,linux,file,iterator,Python,Linux,File,Iterator,我想知道是否有任何有效的方法逐行比较两个大文件 文件1 2 3 2 For i in file 1: line number = 0 For j in file 2: loop until line number == counter else add 1 to line number Compare line 1 increase counter 文件2 2 | haha 3 | hoho 4 | hehe 我只是取每个文

我想知道是否有任何有效的方法逐行比较两个大文件

文件1

2
3
2
For i in file 1: 
    line number = 0
    For j in file 2: 
        loop until line number == counter else add 1 to line number 
        Compare line 1 
    increase counter 
文件2

2 | haha
3 | hoho
4 | hehe
我只是取每个文件的第一个字符并与它们进行比较。目前,我正在使用一种非常简单的方法,在双for循环中迭代它们

喜欢

2
3
2
For i in file 1: 
    line number = 0
    For j in file 2: 
        loop until line number == counter else add 1 to line number 
        Compare line 1 
    increase counter 

将这两个文件读入内存不是一个选项。我在linux上使用python,但我对bash解决方案和python脚本解决方案都持开放态度

这样的东西怎么样:

diff <(cut -c 1 file1.txt) <(cut -c 1 file2.txt)

diff您可以压缩这两个文件并将它们迭代在一起

f1 = open('File 1')
f2 = open('File 2')

flag = True 

for file1_line, file2_line in zip(f1, f2):
  if file1_line[0] != file2_line[0]:
    flag = False
    break

print(flag)

那么您想将每一行与另一个文件中的同一行进行比较<编码>邮政编码
他们@Jornsharpe如果您使用的是2.x,
itertools.izip