Computer >> 컴퓨터 >  >> 프로그램 작성 >> Python

파이썬에서 파일을 비교하는 방법

<시간/>

문제.

파이썬에서 파일을 비교해야 합니다.

해결책..

python의 filecmp 모듈은 파일과 디렉토리를 비교하는 데 사용할 수 있습니다. 1.

cmp(file1, file2[, shallow])

filecmp file1과 file2를 비교하여 동일하면 True, 일치하지 않으면 False를 반환합니다. 기본적으로 os.stat()에 의해 반환된 것과 동일한 속성을 가진 파일은 동일한 것으로 간주됩니다. Shallow가 제공되지 않거나 True이면 동일한 통계 서명을 가진 파일이 동일한 것으로 간주됩니다.

cmpfiles(dir1, dir2, common[, shallow])

두 디렉토리 dir1 및 dir2의 공통 목록에 포함된 파일의 내용을 비교합니다. cmpfiles는 일치, 불일치, 파일 이름 오류의 세 가지 목록을 포함하는 튜플을 반환합니다.

  • match - 두 디렉토리에서 동일한 파일을 나열합니다.

  • 불일치 - 일치하지 않는 파일을 나열합니다.

  • 오류 - 어떤 이유로 비교할 수 없는 파일을 나열합니다.

dircmp(dir1, dir2 [, ignore[, hide]])

디렉터리 dir1 및 dir2에서 다양한 비교 작업을 수행하는 데 사용할 수 있는 디렉터리 비교 개체를 만듭니다.

  • ignore - 무시할 파일 이름 목록을 무시합니다. 기본값은 ['RCS','CVS','tags']입니다.

  • hide - 숨길 파일 이름 목록, 기본값 목록 [os.curdir, os.pardir] (UNIX의 경우 ['.', '..'].

filecmp.dircmp의 인스턴스는 정교한 보고서를 sys.stdout에 인쇄하는 다음 메서드를 구현합니다.

  • report() :두 디렉토리 간의 비교를 인쇄합니다.

  • report_partial_closure() :두 디렉토리와 두 directories.의 바로 하위 디렉토리 비교를 인쇄합니다.

  • report_full_closure() :두 디렉토리, 모든 하위 디렉토리, those subdirectories, and so on (i.e., recursively).

  • left_list:디렉토리 path1에서 발견된 파일 및 하위 디렉토리(hidelist의 요소를 포함하지 않음)

  • right_list:디렉토리 path2에 있는 파일 및 하위 디렉토리(hidelist의 요소를 포함하지 않음)

  • common:디렉토리 path1과 디렉토리 path2 모두에 있는 파일 및 하위 디렉토리.

  • left_only:디렉토리 path1에만 있는 파일 및 하위 디렉토리.

  • right_only:디렉토리 path2에만 있는 파일 및 하위 디렉토리.

  • common_dirs:디렉토리 path1과 디렉토리 path2 모두에 있는 하위 디렉토리.

  • common_files:디렉토리 path1과 디렉토리 path2 모두에 있는 파일.

  • same_files:디렉토리 path1과 디렉토리 path2 모두에서 내용이 동일한 파일의 경로

  • diff_files:디렉토리 path1과 디렉토리 path2에 있지만 내용이 다른 파일의 경로

  • funny_files:디렉토리 path1과 디렉토리 path2에 있지만 어떤 이유로 비교할 수 없는 파일의 경로입니다.

  • subdirs:common_dirs의 이름을 dircmp 개체에 매핑하는 사전입니다.

비교를 위해 테스트 데이터를 준비합니다.

import os
# prepare test data
def makefile(filename,text=None):
"""
Function: make some files
params : input file, body
"""

with open(filename, 'w') as f:
f.write(text or filename)

return

# prepare test data
def makedirectory(directory_name):
"""
Function: make directories
params : input directory
"""
if not os.path.exists(directory_name):
os.mkdir(directory_name)


# Get current working directory
present_directory = os.getcwd()

# change to directory provided
os.chdir(directory_name)

# Make two directories
os.mkdir('dir1')
os.mkdir('dir2')

# Make two same subdirectories
os.mkdir('dir1/common_dir')
os.mkdir('dir2/common_dir')

# Make two different subdirectories
os.mkdir('dir1/dir_only_in_dir1')
os.mkdir('dir2/dir_only_in_dir2')

# Make a unqiue file one each in directory
makefile('dir1/file_only_in_dir1')
makefile('dir2/file_only_in_dir2')

# Make a unqiue file one each in directory
makefile('dir1/common_file', 'Hello, Writing Same Content')
makefile('dir2/common_file', 'Hello, Writing Same Content')

# Make a non unqiue file one each in directory
makefile('dir1/not_the_same')
makefile('dir2/not_the_same')

makefile('dir1/file_in_dir1', 'This is a file in dir1')

os.mkdir('dir2/file_in_dir1')

os.chdir(present_directory)

return

if __name__ == '__main__':
os.chdir(os.getcwd())
makedirectory('example')
makedirectory('example/dir1/common_dir')
makedirectory('example/dir2/common_dir')
  • filecmp 예 filecmp 예제 실행. 얕은 인수는 cmp()에 메타데이터와 함께 파일의 내용을 볼지 여부를 알려줍니다.

기본값은 os.stat()에서 사용할 수 있는 정보를 사용하여 단순 비교를 수행하는 것입니다. 결과가 같으면 파일이 동일한 것으로 간주됩니다. 따라서 같은 시간에 생성된 동일한 크기의 파일은 내용이 달라도 동일한 것으로 보고됩니다.

Shallow가 False이면 파일의 내용이 항상 비교됩니다.

import filecmp

print('Output \n *** Common File :', end=' ')

print(filecmp.cmp('example/dir1/common_file',
'example/dir2/common_file'), end=' ')

print(filecmp.cmp('example/dir1/common_file',
'example/dir2/common_file', shallow=False))

print(' *** Different Files :', end=' ')

print(filecmp.cmp('example/dir1/not_the_same',
'example/dir2/not_the_same'), end=' ')

print(filecmp.cmp('example/dir1/not_the_same',
'example/dir2/not_the_same', shallow=False))

print(' *** Identical Files :', end=' ')

print(filecmp.cmp('example/dir1/file_only_in_dir1',
'example/dir1/file_only_in_dir1'), end=' ')

print(filecmp.cmp('example/dir1/file_only_in_dir1',
'example/dir1/file_only_in_dir1', shallow=False))

출력

*** Common File : True True
*** Different Files : False False
*** Identical Files : True True
  • cmpfile 예:

cmpfiles()를 사용하여 재귀 없이 두 디렉토리에 있는 파일 세트를 비교하십시오.

import filecmp

import os

# Determine the items that exist in both directories.
dir1_contents = set(os.listdir('example/dir1'))
dir2_contents = set(os.listdir('example/dir2'))
common = list(dir1_contents & dir2_contents)

common_files = [f for f in common if os.path.isfile(os.path.join('example/dir1', f))]

print(f' *** Common files are : {common_files}')

# Now, let us compare the directories
match, mismatch, errors = filecmp.cmpfiles(
'example/dir1',
'example/dir2',
common_files,)

print(f' *** Matched files are : {match}')
print(f' *** mismatch files are : {mismatch}')
print(f' *** errors files are : {errors}')
*** Common files are : ['file_in_dir1', 'not_the_same', 'common_file']
*** Matched files are : ['common_file']
*** mismatch files are : ['file_in_dir1', 'not_the_same']
*** errors files are : []

7. 디렉토리 비교.

import filecmp
dc = filecmp.dircmp('example/dir1', 'example/dir2')
print(f"output \n *** Printing detaile report: \n ")
print(dc.report())
print(f"\n")
print(dc.report_full_closure())

출력

*** Printing detaile report:

diff example/dir1 example/dir2
Only in example/dir1 : ['dir_only_in_dir1', 'file_only_in_dir1']
Only in example/dir2 : ['dir_only_in_dir2', 'file_only_in_dir2']
Identical files : ['common_file']
Differing files : ['not_the_same']
Common subdirectories : ['common_dir']
Common funny cases : ['file_in_dir1']
None

diff example/dir1 example/dir2
Only in example/dir1 : ['dir_only_in_dir1', 'file_only_in_dir1']
Only in example/dir2 : ['dir_only_in_dir2', 'file_only_in_dir2']
Identical files : ['common_file']
Differing files : ['not_the_same']
Common subdirectories : ['common_dir']
Common funny cases : ['file_in_dir1']

diff example/dir1\common_dir example/dir2\common_dir
Common subdirectories : ['dir1', 'dir2']

diff example/dir1\common_dir\dir1 example/dir2\common_dir\dir1
Identical files : ['common_file', 'file_in_dir1', 'file_only_in_dir1', 'not_the_same']
Common subdirectories : ['common_dir', 'dir_only_in_dir1']

diff example/dir1\common_dir\dir1\common_dir example/dir2\common_dir\dir1\common_dir

diff example/dir1\common_dir\dir1\dir_only_in_dir1 example/dir2\common_dir\dir1\dir_only_in_dir1

diff example/dir1\common_dir\dir2 example/dir2\common_dir\dir2
Identical files : ['common_file', 'file_only_in_dir2', 'not_the_same']
Common subdirectories : ['common_dir', 'dir_only_in_dir2', 'file_in_dir1']

diff example/dir1\common_dir\dir2\common_dir example/dir2\common_dir\dir2\common_dir

diff example/dir1\common_dir\dir2\dir_only_in_dir2 example/dir2\common_dir\dir2\dir_only_in_dir2

diff example/dir1\common_dir\dir2\file_in_dir1 example/dir2\common_dir\dir2\file_in_dir1
None

Point1에 언급된 모든 명령을 더 시도하여 각 방법이 어떻게 작동하는지 확인할 수 있습니다.