![](/img/trans.png)
[英]Python: Compare two directories with different structure and list new files
[英]Compare files in two directories with python to look for files that are in one directory but not the other -agnostic to subdirectory structure
嘗試將我們當前的項目媒體服務器 (dir1) 與備份 (dir2) 進行比較,以查看刪除了哪些文件。 兩者都是 windows 目錄。 許多文件已被改組到新的子目錄中,但並沒有丟失。 因為使用遞歸和 filecmp.dircmp 更改了目錄結構,所以這篇文章將不起作用: 遞歸比較兩個目錄以確保它們具有相同的文件和子目錄
另一個考慮是不同的文件會有相同的文件名,所以比較需要比較文件大小、修改日期等來確定兩個文件是否相同。
我想要的 sudo 代碼:
def find_missing_files(currentDir, backup):
<does stuff>
return <List of Files in backup that are not in currentDir>
我有的:
def build_file_list(someDir, fileList = []):
for root, dirs, files in os.walk(someDir):
if files:
for file in files:
filePath = os.path.join(root, file)
if filePath not in fileList:
fileList.append(filePath)
return fileList
def cmp_file_lists(dir1, dir2):
dir1List = build_file_list(dir1)
dir2List = build_file_list(dir2)
for dir2file in dir2List:
for dir1file in dir1List:
if filecmp.cmp(dir1file, dir2file):
dir1List.remove(dir1file)
dir2List.remove(dir2file)
break
return (dir1List, dir2List)
編輯:在上面的代碼中,我遇到了一個問題,即 dir2List.remove(dir2file) 拋出 dir2file 不在 dir2List 中的錯誤,因為(它似乎)在某種程度上 dir2list 和 dir1List 都是相同的 object。 不知道這是怎么發生的。
我不知道這是否可以通過 filecmp.dircmp 更輕松地完成,但我錯過了它? 或者如果這是實現我正在尋找的最佳方法? ...或者我應該從 dir2 和我們的 os.walk 中獲取每個文件以在 dir1 中查找它?
我可以建議一個替代方案嗎? 使用pathlib
和它的rglob
方法,一切都容易得多(如果你真的不知道子目錄):
from pathlib import Path
def cmp_file_lists(dir1, dir2):
dir1_filenames = set(f.name for f in Path(dir1).rglob('*'))
dir2_filenames = set(f.name for f in Path(dir2).rglob('*'))
files_in_dir1_but_not_dir2 = dir1_filenames - dir2_filenames
files_in_dir2_but_not_dir1 = dir2_filenames - dir1_filenames
return dir1_filenames, dir2_filenames
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.