filecmp 모듈은 파일과 폴더의 내용을 비교하는 데 사용되며 가벼운 도구이며 사용이 매우 간단합니다. Python 표준 라이브러리는 파일 내용을 비교하기 위한 difflib 모듈도 제공합니다. difflib 모듈에 대해서는 다음번에 분석을 들어보겠습니다.
Filecmp는 파일과 폴더를 편리하게 비교할 수 있는 두 가지 함수를 정의합니다.
filecmp.cmp(f1, f2[,shallow]):
두 파일의 내용이 일치하는지 비교합니다. 매개변수 f1, f2는 비교할 파일의 경로를 지정합니다. 선택적 매개변수인 얕은(shallow)은 파일을 비교할 때 파일 자체의 속성을 고려해야 하는지 여부를 지정합니다(파일 속성은 os.stat 함수를 통해 얻을 수 있음). 파일 내용이 일치하면 함수는 True를 반환하고, 그렇지 않으면 False를 반환합니다.
filecmp.cmpfiles(dir1, dir2, common[,shallow]):
두 폴더의 지정된 파일이 동일한지 비교합니다. 매개변수 dir1 및 dir2는 비교할 폴더를 지정하고, 매개변수 common은 비교할 파일 이름 목록을 지정합니다. 이 함수는 각각 일치, 불일치 및 오류 파일 목록을 나타내는 3개의 목록 요소가 포함된 튜플을 반환합니다. 잘못된 파일이란 존재하지 않는 파일을 의미하거나, 파일을 읽을 수 없는 것으로 판단되거나, 파일을 읽을 수 있는 권한이 없거나, 기타 이유로 파일에 접근할 수 없는 경우를 말합니다.
filecmp 모듈은 폴더 비교를 위한 dircmp 클래스를 정의합니다. 이 클래스를 통해 두 폴더를 비교하면 몇 가지 자세한 비교 결과(예: 폴더 A에만 존재하는 파일 목록)를 얻을 수 있고 하위 파일 재귀 비교를 지원할 수 있습니다. 클립의.
2.filecmpSimple use
2.1 cmpSimple use
Usage: filecmp.cmp(file1, file2), file1과 file2가 동일하면 true를 반환하고, 그렇지 않으면 true를 반환합니다. , false가 반환되는데, 이를 단일 파일의 차이점을 비교한다고 합니다.
2.1.1 복사파일을 두 번 백업
1 # cp /etc/vnc.conf ./2 # cp /etc/vnc.conf ./vnc.conf.bak
2.1.2 쓰기 pythoncode
1 # cat lcmp.py 2 3 #!/usr/bin/env python 4 5 import sys 6 7 import filecmp 8 9 import os10 11 try:12 13 file1 = sys.argv[1]14 15 file2 = sys.argv[2]16 17 except:18 19 print ("Please follow the parameters")20 21 sys.exit()22 23 if os.path.isfile(file1) and os.path.isfile(file2) :24 25 if filecmp.cmp(file1,file2):26 27 print ("Match success")28 29 else :30 31 print ("Match failed")32 33 else:34 35 print ("Please check files")36 37 sys.exit()
2.1.2 스크립트 출력 실행
1 # python lcmp.py vnc.conf vnc.conf.bak 2 Match success
by 항소 결과에서 및 파일을 비교하는 것을 볼 수 있습니다 OK 이제 vnc.conf.bak의 내용을 수정하고
2.1.3 스크립트를 다시 실행
1 # sed -i s/vnc/liwang.org/ vnc.conf.bak2 # python lcmp.py vnc.conf vnc.conf.bak 3 Match failed
match failed가 출력되며 는 스크립트가 Ok의
2.2 cmpfiles단순 사용법
임을 증명합니다. 파일 (DIR1, DIR1, dir2,common[files...]), 해당 기능은 dir1과 dir2 디렉터리 간의 차이점을 비교하는 것입니다. 이 메서드는 일치, 불일치 및 오류라는 세 가지 목록을 반환합니다.2.2.1 파일 복사
1 # mkdir -p dir1 dir22 # cp lcmp.py vnc.conf vnc.conf.bak dir1/3 # cp lcmp.py vnc.conf dir2/
pythoncode 1 # cat lcmpfiles.py 2 3 #!/usr/bin/env python 4 5 import os 6 7 import filecmp 8 9 import sys10 11 dir1 = input("Please enter a folder to match:")12 13 dir2 = input("Please enter a folder to match:")14 15 files = []16 17 while True:18 19 local_files = input("Please enter the file to compare:[n/N Exit the input]")20 21 if local_files == 'N' or local_files == 'n':22 23 break24 25 elif local_files == '':26 27 continue28 29 else :30 31 files.append(local_files)32 33 try:34 35 os.path.exists(dir1)36 37 os.path.exists(dir2)38 39 except:40 41 print ("Pleae check the folder.")42 43 sys.exit()44 45 #print (filecmp.cmpfiles(dir1,dir2,files)[0])46 47 print ("It's file match:",filecmp.cmpfiles(dir1,dir2,files)[0])48 49 print ("The file does not match:",filecmp.cmpfiles(dir1,dir2,files)[1])50 51 print ("File does not exists:",filecmp.cmpfiles(dir1,dir2,files)[2])
스크립트를 실행(왜냐하면 입력 사용) 1 # python3 lcmpfiles.py
2 Please enter a folder to match:dir1 3 Please enter a folder to match:dir2 4 Please enter the file to compare:[n/N Exit the input]lcmp.py 5 Please enter the file to compare:[n/N Exit the input]vnc.conf 6 Please enter the file to compare:[n/N Exit the input]vnc.conf.bak 7 Please enter the file to compare:[n/N Exit the input]n 8 It's file match: ['lcmp.py', 'vnc.conf'] 9 The file does not match: []10 File does not exists: ['vnc.conf.bak']
可以看出,lcmp.py 和 vnc.conf 在dir1 和dr2都有,且文件内容相同,而vnc.conf.bak在dir1有,dir没有,故输出,文件匹配:lcmp.py和vnc.conf ,文件不存在:vnc.conf.bak,文件不相同:无
2.2 dircmp的简单使用
语法:dircmp(a,b,[,ignore[,hide]]) 其中a,b是文件名,ignore是可以忽略的列表,hide代表隐藏列表,dircmp可以获得目录比较详细的信息,同时还支持递归。
dircmp提供了三个输出方法:
report() 比较当前指定目录中的内容
report_full_closure() 递归比较所有指定文件的内容
2.2.1 模拟环境
1 # ls dir1/ dir2/2 dir1/:3 hosts ld.so.conf sysconfig4 5 dir2/:6 hosts ld.so.conf sysconfig
其中,sysconfig 是一个目录 hosts 和 ld.so.conf都是文件,且hosts内容不一致 sysconfig中的文件也不一样
2.2.2 编写python代码
2.2.2.1 dircmp.report()
1 # cat simple_filecmp.py 2 3 #!/usr/bin/env python 4 5 import filecmp 6 7 dir1 = "/root/python/d_2_filecmp/cmp/dir2" 8 9 dir2 = "/root/python/d_2_filecmp/cmp/dir1"10 11 dirobj = filecmp.dircmp(dir1,dir2)12 13 print (dirobj.report())
2.2.2.2 执行脚本
1 # python simple_filecmp.py 2 diff /root/python/d_2_filecmp/cmp/dir2 /root/python/d_2_filecmp/cmp/dir13 Identical files : ['ld.so.conf']4 Differing files : ['hosts']5 Common subdirectories : ['sysconfig']6 None7 [root@localhost cmp]# cat simple_filecmp.py
由上面的结果,我们可以看出,report只能比对脚本的首层目录,而无法对子文件夹下的目录进行匹配
2.2.2.3 report_full_closure()
1 # cat simple_filecmp_2.py 2 3 #!/usr/bin/env python 4 5 import filecmp 6 7 dir1 = "/root/python/d_2_filecmp/cmp/dir1/" 8 9 dir2 = "/root/python/d_2_filecmp/cmp/dir2/"10 11 dirobj = filecmp.dircmp(dir1,dir2)12 13 print (dirobj.report_full_closure())
2.2.2.4 执行脚本
1 diff /root/python/d_2_filecmp/cmp/dir1/ /root/python/d_2_filecmp/cmp/dir2/2 Identical files : ['ld.so.conf']3 Differing files : ['hosts']4 Common subdirectories : ['sysconfig']5 6 diff/root/python/d_2_filecmp/cmp/dir1/sysconfig /root/python/d_2_filecmp/cmp/dir2/sysconfig7 ......
由此可见差别report()和report_full_closure()的差别在于
3.filecmp案例
3.1 需求
需求:1.备份etc 文件夹下所有的内容,并且保持实时备份,如果有新的文件,则copy至备份文件中,如果有新的,则update之
3.2 流程图
3.2.1 初步流程图:
3.2.2 对比文件差异流程图
3.3 代码编写:
3.3.1 补充知识:
dircmp.left_only
只在左边出现的文件
1 # cat simple_filecmp_3.py 2 3 #!/usr/bin/env python 4 5 import filecmp 6 7 dir1 = "/root/python/d_2_filecmp/cmp/dir1/" 8 9 dir2 = "/root/python/d_2_filecmp/cmp/dir2/"10 11 dirobj = filecmp.dircmp(dir1,dir2)12 13 print (dirobj.diff_files)
执行结果
1 # ls dir1 dir2/2 dir1:3 hosts ld.so.conf sysconfig teacher4 5 dir2/:6 hosts ld.so.conf sysconfig7 [root@localhost cmp]# python simple_filecmp_3.py 8 ['teacher']
由上诉可见,当teacher只出现在dir1时,则会被抓取出来,所谓的left和right是相对于filecmp.dircmp而言的
dircmp.diff_files
返回不能匹配额文件
1 # cat simple_filecmp_3.py 2 3 #!/usr/bin/env python 4 5 import filecmp 6 7 dir1 = "/root/python/d_2_filecmp/cmp/dir1/" 8 9 dir2 = "/root/python/d_2_filecmp/cmp/dir2/"10 11 dirobj = filecmp.dircmp(dir1,dir2)12 13 print (dirobj.diff_files)14 15 #print (dirobj.left_only)
执行结果
1 [root@localhost cmp]# ls dir1 dir22 dir1:3 hosts ld.so.conf sysconfig teacher4 5 dir2:6 hosts ld.so.conf sysconfig7 [root@localhost cmp]# python simple_filecmp_3.py 8 ['hosts']9 [root@localhost cmp]#
之前我们修改过hosts的文件,文件内容已经不一致,现在已经被抓取出来了
3.3.2 编写自动备份脚本
1 # cat d_7_12_filecmp.py 2 #!/usr/bin/env python 3 4 import filecmp 5 import os 6 import sys 7 import shutil 8 9 source_files = "/root/python/d_2_filecmp/dir1"10 target_files = "/root/python/d_2_filecmp/dir2"11 12 def check_common_dirs(source_files,target_files):13 dirsobj = filecmp.dircmp(source_files , target_files)14 15 common_dirs_list = dirsobj.common_dirs16 17 for common_line in common_dirs_list :18 files_contrast('/'+source_files+'/'+common_line,'/'+target_files+'/'+common_line)19 20 def files_contrast(dir1,dir2) :21 22 dirobj = filecmp.dircmp(dir1,dir2)23 24 no_exists_files = dirobj.left_only25 no_diff_files = dirobj.diff_files26 27 for exists_files in no_exists_files :28 29 if os.path.isfile(exists_files) :30 shutil.copyfile ('/'+dir1+'/'+exists_files , '/'+dir2+'/'+exists_files)31 else :32 print ("%s is dirctory" %(exists_files))33 os.makedirs('/'+dir2+'/'+exists_files)34 print ("%s is mkdirs" %('/'+target_files+'/'+exists_files))35 36 try :37 print ("values : %s %s" %('/'+dir1+'/'+exists_files , '/'+dir2+'/'+exists_files))38 files_contrast('/'+dir1+'/'+exists_files , '/'+dir2+'/'+exists_files)39 except :40 return 41 42 for diff_files in no_diff_files :43 if os.path.isfile(diff_files) :44 os.remove('/'+dir2+'/'+diff_files)45 shutil.copyfile ('/'+dir1+'/'+diff_files , '/'+dir2+'/'+diff_files)46 47 if os.path.exists(source_files) :48 49 if os.path.exists(target_files) == "False" :50 os.makedirs(target_files)51 52 files_contrast(source_files,target_files) 53 check_common_dirs(source_files,target_files)54 55 else :56 print ("Soure files no exists")57 sys.exit()
3.4 执行脚本输出
3.4.1 查看文件
可知 dir2下没有任何文件
1 # tree dir1/ dir2/ 2 dir1/ 3 ├── 123 4 │ └── 123456 5 ├── 4556 6 │ └── 789 7 │ └── d 8 ├── lcmp.py 9 ├── vnc.conf10 └── vnc.conf.bak11 dir2/12 13 3 directories, 5 files
3.4.2 执行脚本
1 root@localhost d_2_filecmp]# python d_7_12_filecmp.py 2 4556 is dirctory 3 //root/python/d_2_filecmp/dir2/4556 is mkdirs 4 values : //root/python/d_2_filecmp/dir1/4556 //root/python/d_2_filecmp/dir2/4556 5 789 is dirctory 6 //root/python/d_2_filecmp/dir2/789 is mkdirs 7 values : ///root/python/d_2_filecmp/dir1/4556/789 ///root/python/d_2_filecmp/dir2/4556/789 8 d is dirctory 9 //root/python/d_2_filecmp/dir2/d is mkdirs10 values : ////root/python/d_2_filecmp/dir1/4556/789/d ////root/python/d_2_filecmp/dir2/4556/789/d11 123 is dirctory12 //root/python/d_2_filecmp/dir2/123 is mkdirs13 values : //root/python/d_2_filecmp/dir1/123 //root/python/d_2_filecmp/dir2/12314 123456 is dirctory15 //root/python/d_2_filecmp/dir2/123456 is mkdirs16 values : ///root/python/d_2_filecmp/dir1/123/123456 ///root/python/d_2_filecmp/dir2/123/123456
可以看出,备份的信息,前面的多个/可以不必理会,linux只识别一个/
3.4.3 查看备份效果
1 # tree dir1/ dir2/ 2 dir1/ 3 ├── 123 4 │ └── 123456 5 ├── 4556 6 │ └── 789 7 │ └── d 8 ├── lcmp.py 9 ├── vnc.conf10 └── vnc.conf.bak11 dir2/12 ├── 12313 │ └── 12345614 ├── 455615 │ └── 78916 │ └── d17 ├── lcmp.py18 ├── vnc.conf19 └── vnc.conf.bak20 21 8 directories, 8 files
由上,可知,备份完全成功,针对于定时执行python脚本,可以将脚本写入crontab中,开启定时任务即可。
위 내용은 Python에서 filecmp를 간단하게 사용의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

Python의 유연성은 다중 파리가 지원 및 동적 유형 시스템에 반영되며, 사용 편의성은 간단한 구문 및 풍부한 표준 라이브러리에서 나옵니다. 유연성 : 객체 지향, 기능 및 절차 프로그래밍을 지원하며 동적 유형 시스템은 개발 효율성을 향상시킵니다. 2. 사용 편의성 : 문법은 자연 언어에 가깝고 표준 라이브러리는 광범위한 기능을 다루며 개발 프로세스를 단순화합니다.

Python은 초보자부터 고급 개발자에 이르기까지 모든 요구에 적합한 단순성과 힘에 호의적입니다. 다목적 성은 다음과 같이 반영됩니다. 1) 배우고 사용하기 쉽고 간단한 구문; 2) Numpy, Pandas 등과 같은 풍부한 라이브러리 및 프레임 워크; 3) 다양한 운영 체제에서 실행할 수있는 크로스 플랫폼 지원; 4) 작업 효율성을 향상시키기위한 스크립팅 및 자동화 작업에 적합합니다.

예, 하루에 2 시간 후에 파이썬을 배우십시오. 1. 합리적인 학습 계획 개발, 2. 올바른 학습 자원을 선택하십시오. 3. 실습을 통해 학습 된 지식을 통합하십시오. 이 단계는 짧은 시간 안에 Python을 마스터하는 데 도움이 될 수 있습니다.

Python은 빠른 개발 및 데이터 처리에 적합한 반면 C는 고성능 및 기본 제어에 적합합니다. 1) Python은 간결한 구문과 함께 사용하기 쉽고 데이터 과학 및 웹 개발에 적합합니다. 2) C는 고성능과 정확한 제어를 가지고 있으며 게임 및 시스템 프로그래밍에 종종 사용됩니다.

Python을 배우는 데 필요한 시간은 개인마다 다릅니다. 주로 이전 프로그래밍 경험, 학습 동기 부여, 학습 리소스 및 방법 및 학습 리듬의 영향을받습니다. 실질적인 학습 목표를 설정하고 실용적인 프로젝트를 통해 최선을 다하십시오.

파이썬은 자동화, 스크립팅 및 작업 관리가 탁월합니다. 1) 자동화 : 파일 백업은 OS 및 Shutil과 같은 표준 라이브러리를 통해 실현됩니다. 2) 스크립트 쓰기 : PSUTIL 라이브러리를 사용하여 시스템 리소스를 모니터링합니다. 3) 작업 관리 : 일정 라이브러리를 사용하여 작업을 예약하십시오. Python의 사용 편의성과 풍부한 라이브러리 지원으로 인해 이러한 영역에서 선호하는 도구가됩니다.

제한된 시간에 Python 학습 효율을 극대화하려면 Python의 DateTime, Time 및 Schedule 모듈을 사용할 수 있습니다. 1. DateTime 모듈은 학습 시간을 기록하고 계획하는 데 사용됩니다. 2. 시간 모듈은 학습과 휴식 시간을 설정하는 데 도움이됩니다. 3. 일정 모듈은 주간 학습 작업을 자동으로 배열합니다.

Python은 게임 및 GUI 개발에서 탁월합니다. 1) 게임 개발은 Pygame을 사용하여 드로잉, 오디오 및 기타 기능을 제공하며 2D 게임을 만드는 데 적합합니다. 2) GUI 개발은 Tkinter 또는 PYQT를 선택할 수 있습니다. Tkinter는 간단하고 사용하기 쉽고 PYQT는 풍부한 기능을 가지고 있으며 전문 개발에 적합합니다.


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

MinGW - Windows용 미니멀리스트 GNU
이 프로젝트는 osdn.net/projects/mingw로 마이그레이션되는 중입니다. 계속해서 그곳에서 우리를 팔로우할 수 있습니다. MinGW: GCC(GNU Compiler Collection)의 기본 Windows 포트로, 기본 Windows 애플리케이션을 구축하기 위한 무료 배포 가능 가져오기 라이브러리 및 헤더 파일로 C99 기능을 지원하는 MSVC 런타임에 대한 확장이 포함되어 있습니다. 모든 MinGW 소프트웨어는 64비트 Windows 플랫폼에서 실행될 수 있습니다.

에디트플러스 중국어 크랙 버전
작은 크기, 구문 강조, 코드 프롬프트 기능을 지원하지 않음

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

SublimeText3 Linux 새 버전
SublimeText3 Linux 최신 버전

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경
