如何使用Python filecmp对比文件夹两个版本并获取差异文件名?
Let's break down what's going on with your current code and fix your file comparison issue! The core problem here is that Python's filecmp.dircmp only checks for differences in the top-level directory by default — it won't automatically dig into subfolders like sub_folder to detect changes in bar.json. That's why you're likely missing some of the differing files between your two folder versions.
How to Fix It: Recursively Check All Subdirectories
We need to build a recursive function that digs into each subdirectory identified by dircmp and collects all differing files (including those in nested folders). Here's a complete, robust solution:
import filecmp from pathlib import Path def get_all_diff_files(left_dir: str, right_dir: str) -> list[str]: """Recursively collect all files with content differences between two directories.""" diff_files = [] cmp = filecmp.dircmp(left_dir, right_dir) # Add files with differing content in the current directory for file in cmp.diff_files: diff_files.append(str(Path(left_dir) / file)) # Optional: Uncomment below to include files that exist only in one directory # for file in cmp.left_only: # diff_files.append(str(Path(left_dir) / file)) # for file in cmp.right_only: # diff_files.append(str(Path(right_dir) / file)) # Recursively check all shared subdirectories for subdir in cmp.common_dirs: left_subdir = str(Path(left_dir) / subdir) right_subdir = str(Path(right_dir) / subdir) diff_files.extend(get_all_diff_files(left_subdir, right_subdir)) return diff_files # Example usage matching your folder structure main_folder_v1 = "main_folder_v1" main_folder_v2 = "main_folder_v2" all_differing_files = get_all_diff_files(main_folder_v1, main_folder_v2) print("Files with content differences:") for file in all_differing_files: print(f"- {file}")
Key Details to Note:
- Recursive Traversal: The function iterates through
common_dirs(subdirectories present in both versions) and recursively checks each one for differences. - Targeted Diff Capture:
cmp.diff_filesspecifically grabs files that exist in both directories but have different content — exactly what you requested. - Cross-Platform Compatibility: Using
pathlib.Pathensures the code works seamlessly on Windows, macOS, and Linux. - Optional Extras: I commented out code to capture files that exist only in one version (
left_only/right_only) — uncomment those lines if you want to include those edge cases too.
Why Your Original Code Failed
Your initial code only pulled diff_files from the top-level directory. So if bar.json in sub_folder was modified between versions, it wouldn't show up unless you explicitly checked the subdirectory's dircmp object. The recursive approach fixes this gap.
内容的提问来源于stack exchange,提问作者Andersson

