Computer >> Máy Tính >  >> Lập trình >> Python

Cách so sánh các tệp trong Python

Vấn đề.

Bạn cần so sánh các tệp bằng Python.

Giải pháp ..

Mô-đun filecmp trong python có thể được sử dụng để so sánh các tệp và thư mục. 1.

cmp(file1, file2[, shallow])

filecmp So sánh các tệp file1 và file2 và trả về True nếu giống nhau, False nếu không. Theo mặc định, các tệp có các thuộc tính giống nhau được trả về bởi os.stat () được coi là bằng nhau. Nếu cạn không được cung cấp (hoặc là True), các tệp có cùng chữ ký thống kê được coi là bình đẳng.

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

So sánh nội dung của các tệp có trong danh sách chung trong hai thư mục dir1 và dir2. cmpfiles trả về một bộ chứa ba danh sách - trùng khớp, không khớp, lỗi tên tệp.

  • khớp - liệt kê các tệp giống nhau trong cả hai thư mục.

  • không khớp - liệt kê các tệp không khớp.

  • lỗi - liệt kê các tệp không thể so sánh được vì một số lý do.

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

Tạo một đối tượng so sánh thư mục có thể được sử dụng để thực hiện các thao tác so sánh khác nhau trên các thư mục dir1 và dir2.

  • bỏ qua - bỏ qua danh sách tên tệp cần bỏ qua, giá trị mặc định của ['RCS', 'CVS', 'thẻ'].

  • ẩn - danh sách tên tệp cần ẩn, danh sách mặc định [os.curdir, os.pardir] (['.', '..'] trên UNIX.

Các phiên bản của filecmp.dircmp triển khai các phương thức sau để in các báo cáo được soạn thảo tới sys.stdout:

  • report ():In bản so sánh giữa hai thư mục.

  • report_partial_closure ():In bản so sánh của hai thư mục cũng như của các thư mục con ngay lập tức của hai directories.

  • report_full_closure ():In bản so sánh của hai thư mục, tất cả các thư mục con của chúng, tất cả các thư mục con của those subdirectories, and so on (i.e., recursively).

  • left_list:các tệp và thư mục con được tìm thấy trong thư mục path1, không bao gồm các phần tử của danh sách ẩn.

  • right_list:các tệp và thư mục con được tìm thấy trong thư mục path2, không bao gồm các phần tử của danh sách ẩn.

  • common:các tệp và thư mục con nằm trong cả đường dẫn thư mục1 và đường dẫn thư mục2.

  • left_only:tệp và thư mục con chỉ có trong thư mục path1.

  • right_only:các tệp và thư mục con chỉ có trong thư mục path2.

  • common_dirs:thư mục con nằm trong cả đường dẫn thư mục1 và đường dẫn thư mục2.

  • common_files:các tệp nằm trong cả đường dẫn thư mục1 và đường dẫn thư mục2.

  • same_files:Đường dẫn đến các tệp có nội dung giống hệt nhau trong cả đường dẫn thư mục1 và đường dẫn thư mục2.

  • diff_files:Đường dẫn đến các tệp nằm trong cả đường dẫn thư mục1 và đường dẫn thư mục2 nhưng có nội dung khác nhau.

  • funny_files:đường dẫn đến các tệp nằm trong cả đường dẫn thư mục1 và đường dẫn thư mục2 nhưng không thể so sánh được vì lý do nào đó.

  • subdirs:Từ điển ánh xạ các tên trong common_dirs với các đối tượng dircmp.

Chuẩn bị dữ liệu thử nghiệm để so sánh.

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')
  • ví dụ về filecmp Chạy filecmp ví dụ. Đối số nông cho cmp () biết liệu có nên xem nội dung của tệp, ngoài siêu dữ liệu của nó hay không.

Mặc định là thực hiện một phép so sánh nông bằng cách sử dụng thông tin có sẵn từ os.stat (). Nếu kết quả giống nhau, các tệp được coi là giống nhau. Do đó, các tệp có cùng kích thước được tạo cùng lúc được báo cáo là giống nhau, ngay cả khi nội dung của chúng khác nhau.

Khi nông là Sai, nội dung của tệp luôn được so sánh.

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))

Đầu ra

*** Common File : True True
*** Different Files : False False
*** Identical Files : True True
  • cmpfiles Ví dụ:

Sử dụng cmpfiles () để so sánh một tập hợp các tệp trong hai thư mục mà không cần đệ quy.

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. So sánh các thư mục.

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())

Đầu ra

*** 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

Bạn có thể thử thêm tất cả các lệnh được đề cập trong Point1 để xem mỗi phương thức hoạt động như thế nào.