Python에서는 두 텍스트 파일의 내용이 동일한 지 비교하는 간결한 방법이 있습니까?

StackOverflow https://stackoverflow.com/questions/254350

  •  05-07-2019
  •  | 
  •  

문제

차이점이 무엇인지 상관하지 않습니다. 내용이 다른지 알고 싶습니다.

도움이 되었습니까?

해결책

낮은 레벨 방법 :

from __future__ import with_statement
with open(filename1) as f1:
   with open(filename2) as f2:
      if f1.read() == f2.read():
         ...

높은 수준의 방법 :

import filecmp
if filecmp.cmp(filename1, filename2, shallow=False):
   ...

다른 팁

기본 효율성을 원한다면 먼저 파일 크기를 확인하고 싶을 것입니다.

if os.path.getsize(filename1) == os.path.getsize(filename2):
  if open('filename1','r').read() == open('filename2','r').read():
    # Files are the same.

이렇게하면 크기가 같지 않은 두 파일의 모든 줄을 읽을 수 있으므로 동일 할 수는 없습니다.

(그 이상으로, 각 파일의 빠른 MD5SUM을 호출하여 비교할 수는 있지만 "파이썬에서"가 아니므로 여기서 멈출 것입니다.)

기능 스타일 파일 비교 기능입니다. 파일의 크기가 다른 경우 즉시 False가 반환됩니다. 그렇지 않으면 4kib 블록 크기로 읽히고 첫 번째 차이점에 즉시 False를 반환합니다.

from __future__ import with_statement
import os
import itertools, functools, operator

def filecmp(filename1, filename2):
    "Do the two files have exactly the same contents?"
    with open(filename1, "rb") as fp1, open(filename2, "rb") as fp2:
        if os.fstat(fp1.fileno()).st_size != os.fstat(fp2.fileno()).st_size:
            return False # different sizes ∴ not equal
        fp1_reader= functools.partial(fp1.read, 4096)
        fp2_reader= functools.partial(fp2.read, 4096)
        cmp_pairs= itertools.izip(iter(fp1_reader, ''), iter(fp2_reader, ''))
        inequalities= itertools.starmap(operator.ne, cmp_pairs)
        return not any(inequalities)

if __name__ == "__main__":
    import sys
    print filecmp(sys.argv[1], sys.argv[2])

그냥 다른 테이크 :)

다른 사람들의 답변에 대해 언급 할 수 없으므로 내 자신을 쓸 것입니다.

MD5를 사용하는 경우 너무 많은 메모리를 사용하므로 MD5.UPDATE (F.READ ())만으로는 반드시 반드시 있어야합니다.

def get_file_md5(f, chunk_size=8192):
    h = hashlib.md5()
    while True:
        chunk = f.read(chunk_size)
        if not chunk:
            break
        h.update(chunk)
    return h.hexdigest()

f = open(filename1, "r").read()
f2 = open(filename2,"r").read()
print f == f2


더 큰 파일의 경우 a를 계산할 수 있습니다 MD5 또는 파일 해시.

MD5를 사용하여 파일 내용의 해시를 사용합니다.

import hashlib

def checksum(f):
    md5 = hashlib.md5()
    md5.update(open(f).read())
    return md5.hexdigest()

def is_contents_same(f1, f2):
    return checksum(f1) == checksum(f2)

if not is_contents_same('foo.txt', 'bar.txt'):
    print 'The contents are not the same!'
from __future__ import with_statement

filename1 = "G:\\test1.TXT"

filename2 = "G:\\test2.TXT"


with open(filename1) as f1:

   with open(filename2) as f2:

      file1list = f1.read().splitlines()

      file2list = f2.read().splitlines()

      list1length = len(file1list)

      list2length = len(file2list)

      if list1length == list2length:

          for index in range(len(file1list)):

              if file1list[index] == file2list[index]:

                   print file1list[index] + "==" + file2list[index]

              else:                  

                   print file1list[index] + "!=" + file2list[index]+" Not-Equel"

      else:

          print "difference inthe size of the file and number of lines"
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top