如何匹配两目录下相对路径一致的文件并传递绝对路径到比对函数
实现思路
你现在的代码首先要修复一个隐性bug:拼接相对路径的时候没有加路径分隔符,会导致相对路径计算错误,比如目录src/sub下的a.txt会被拼成src/suba.txt,正确拼接要用os.path.join。
你不需要维护四个列表来存路径,直接用字典做相对路径到绝对路径的映射,查找匹配的效率会高很多,具体实现步骤如下:
- 遍历源目录生成「相对路径: 绝对路径」的映射字典,过滤掉
.git、.idea这类不需要比对的目录 - 遍历目标目录,每生成一个文件的相对路径就去源目录的映射字典里查
- 能查到说明两个文件相对路径匹配,直接把对应的两个绝对路径传入
compare_all_files函数即可
完整可运行代码
import os def compare_all_files(source, target): """ The File comparison is done here """ print(f"正在比对:\n源文件:{source}\n目标文件:{target}\n") def match_files_from_directories(source_root: str, target_root: str) -> bool: """推导所有文件的相对路径,匹配后调用比对函数""" # 源目录 相对路径->绝对路径 映射表 source_rel_map = {} # 遍历源目录生成映射 for dir_name, sub_dirs, files in os.walk(source_root): # 过滤不需要扫描的目录 sub_dirs[:] = [d for d in sub_dirs if d not in (".git", ".idea")] for file in files: abs_path = os.path.join(dir_name, file) # 计算正确的相对路径 rel_path = os.path.relpath(abs_path, source_root) # 如果你确实需要去掉相对路径开头的./ 可以用下面这句代替 # rel_path = rel_path.lstrip(os.sep + '.') source_rel_map[rel_path] = abs_path # 遍历目标目录匹配文件 for dir_name, sub_dirs, files in os.walk(target_root): sub_dirs[:] = [d for d in sub_dirs if d not in (".git", ".idea")] for file in files: abs_path = os.path.join(dir_name, file) rel_path = os.path.relpath(abs_path, target_root) # 和上面源目录的处理保持一致,如果源端处理了开头的点这里也要同步处理 # rel_path = rel_path.lstrip(os.sep + '.') # 相对路径匹配,调用比对函数 if rel_path in source_rel_map: compare_all_files(source_rel_map[rel_path], abs_path) return True # 调用示例 source_path = '/home/user/Downloads/Test' target_path = '/home/user/Downloads/SampleCode/Test' match_files_from_directories(source_path, target_path)
补充说明
如果你要保留你原来的四个列表的实现逻辑,也可以用下面的方法找匹配对:
# 先把target的相对路径和绝对路径也做成映射 target_rel_map = {rel: abs_p for rel, abs_p in zip(rel_target_path_list, abs_target_path_list)} # 找两个目录共有的相对路径 common_rel_paths = set(rel_source_path_list_1) & set(rel_target_path_list) # 遍历共有路径调用比对函数 for rel in common_rel_paths: compare_all_files( abs_source_path_list[rel_source_path_list_1.index(rel)], target_rel_map[rel] )
不过这种列表遍历查找的效率比字典低,目录文件多的时候不推荐用。
内容的提问来源于stack exchange,提问作者user932061
相关产品推荐
相关产品推荐

