首頁 後端開發 Python教學 Python中filecmp的簡單使用

Python中filecmp的簡單使用

Jul 19, 2017 pm 11:30 PM
python

    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個list元素的元組,分別表示符合、不符、錯誤的檔案清單。錯誤的文件指的是不存在的文件,或文件被瑣定不可讀,或沒權限讀文件,或因其他原因而存取不了該文件。

    filecmp模組中定義了一個dircmp類,用於比較資料夾,透過該類別比較兩個資料夾,可以取得一些詳細的比較結果(如只在A資料夾存在的檔案清單),並支援子資料夾的遞歸比較。

2.filecmp的簡單使用

#2.1 cmp的簡單使用

用法:filecmp.cmp(file1,file2),如果file1和file2相同的話,則會傳回true,否則傳回false,這就稱為比較單一檔案的差異。

2.1.1 copy一個檔案備份兩次

1 # cp /etc/vnc.conf ./2 # cp /etc/vnc.conf ./vnc.conf.bak
登入後複製

2.1.2 python程式碼

 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
登入後複製

##由上訴結果可以看出,檔案是比較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

的簡單使用

用法

:filecmp.cmpfiles(dir1,dir2,common[files...]),作用是對比dir1 和dir2 目錄的差異,該方法會傳回三個list,分別是匹配,不匹配,錯誤。 2.2.1

複製檔案

1 # mkdir -p dir1 dir22 # cp lcmp.py vnc.conf vnc.conf.bak dir1/3 # cp lcmp.py vnc.conf dir2/
登入後複製
2.2.2

python#程式碼

 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])
登入後複製
2.2.3

python3執行腳本##(因為使用了input)

 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,则会被抓取出来,所谓的leftright是相对于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中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
4 週前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
4 週前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您聽不到任何人,如何修復音頻
4 週前 By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解鎖Myrise中的所有內容
1 個月前 By 尊渡假赌尊渡假赌尊渡假赌

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

HadiDB:Python 中的輕量級、可水平擴展的數據庫 HadiDB:Python 中的輕量級、可水平擴展的數據庫 Apr 08, 2025 pm 06:12 PM

HadiDB:輕量級、高水平可擴展的Python數據庫HadiDB(hadidb)是一個用Python編寫的輕量級數據庫,具備高度水平的可擴展性。安裝HadiDB使用pip安裝:pipinstallhadidb用戶管理創建用戶:createuser()方法創建一個新用戶。 authentication()方法驗證用戶身份。 fromhadidb.operationimportuseruser_obj=user("admin","admin")user_obj.

Python:探索其主要應用程序 Python:探索其主要應用程序 Apr 10, 2025 am 09:41 AM

Python在web開發、數據科學、機器學習、自動化和腳本編寫等領域有廣泛應用。 1)在web開發中,Django和Flask框架簡化了開發過程。 2)數據科學和機器學習領域,NumPy、Pandas、Scikit-learn和TensorFlow庫提供了強大支持。 3)自動化和腳本編寫方面,Python適用於自動化測試和系統管理等任務。

2小時的Python計劃:一種現實的方法 2小時的Python計劃:一種現實的方法 Apr 11, 2025 am 12:04 AM

2小時內可以學會Python的基本編程概念和技能。 1.學習變量和數據類型,2.掌握控制流(條件語句和循環),3.理解函數的定義和使用,4.通過簡單示例和代碼片段快速上手Python編程。

Navicat查看MongoDB數據庫密碼的方法 Navicat查看MongoDB數據庫密碼的方法 Apr 08, 2025 pm 09:39 PM

直接通過 Navicat 查看 MongoDB 密碼是不可能的,因為它以哈希值形式存儲。取回丟失密碼的方法:1. 重置密碼;2. 檢查配置文件(可能包含哈希值);3. 檢查代碼(可能硬編碼密碼)。

如何將 AWS Glue 爬網程序與 Amazon Athena 結合使用 如何將 AWS Glue 爬網程序與 Amazon Athena 結合使用 Apr 09, 2025 pm 03:09 PM

作為數據專業人員,您需要處理來自各種來源的大量數據。這可能會給數據管理和分析帶來挑戰。幸運的是,兩項 AWS 服務可以提供幫助:AWS Glue 和 Amazon Athena。

如何針對高負載應用程序優化 MySQL 性能? 如何針對高負載應用程序優化 MySQL 性能? Apr 08, 2025 pm 06:03 PM

MySQL數據庫性能優化指南在資源密集型應用中,MySQL數據庫扮演著至關重要的角色,負責管理海量事務。然而,隨著應用規模的擴大,數據庫性能瓶頸往往成為製約因素。本文將探討一系列行之有效的MySQL性能優化策略,確保您的應用在高負載下依然保持高效響應。我們將結合實際案例,深入講解索引、查詢優化、數據庫設計以及緩存等關鍵技術。 1.數據庫架構設計優化合理的數據庫架構是MySQL性能優化的基石。以下是一些核心原則:選擇合適的數據類型選擇最小的、符合需求的數據類型,既能節省存儲空間,又能提升數據處理速度

redis怎麼啟動服務器 redis怎麼啟動服務器 Apr 10, 2025 pm 08:12 PM

啟動 Redis 服務器的步驟包括:根據操作系統安裝 Redis。通過 redis-server(Linux/macOS)或 redis-server.exe(Windows)啟動 Redis 服務。使用 redis-cli ping(Linux/macOS)或 redis-cli.exe ping(Windows)命令檢查服務狀態。使用 Redis 客戶端,如 redis-cli、Python 或 Node.js,訪問服務器。

redis怎麼讀取隊列 redis怎麼讀取隊列 Apr 10, 2025 pm 10:12 PM

要從 Redis 讀取隊列,需要獲取隊列名稱、使用 LPOP 命令讀取元素,並處理空隊列。具體步驟如下:獲取隊列名稱:以 "queue:" 前綴命名,如 "queue:my-queue"。使用 LPOP 命令:從隊列頭部彈出元素並返回其值,如 LPOP queue:my-queue。處理空隊列:如果隊列為空,LPOP 返回 nil,可先檢查隊列是否存在再讀取元素。

See all articles