【问题标题】:Comparing tow large files line by line逐行比较两个大文件
【发布时间】:2015-12-02 15:10:21
【问题描述】:

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

文件 1

2
3
2

文件 2

2 | haha
3 | hoho
4 | hehe

我只是取每个文件的第一个字符并与它们进行比较。目前我正在使用一种非常幼稚的方法在双 for 循环中迭代它们。

喜欢

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 脚本解决方案都持开放态度

【问题讨论】:

  • 所以你想将每一行与另一个文件中的同一行进行比较? zip他们!
  • @Jornsharpe 我无法压缩它们,因为我无法将它们加载到内存中
  • 如果你使用的是 2.x,itertools.izip他们

标签: python linux file iterator


【解决方案1】:

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

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)

【讨论】:

    【解决方案2】:

    这样的事情怎么样:

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

    diff 是您用来比较文件行的工具。您可以使用process substitution(匿名管道)来比较每个文件的仅包含第一个字符的版本(使用cut)。

    【讨论】:

      猜你喜欢
      • 2014-08-24
      • 2018-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-27
      • 1970-01-01
      相关资源
      最近更新 更多