python script:
find_and_compare.py
import os
import difflib
def find_and_compare(root_folder, target_filename, output_file):
# 用于存储文件路径及文件名
file_paths = []
# 用于存储 common_ctrl.v 文件的内容
file_contents = {}
# 用于记录已经比较过的文件对
compared_files = set()
# 遍历文件夹
for foldername, subfolders, filenames in os.walk(root_folder):
for filename in filenames:
if filename == target_filename:
file_path = os.path.join(foldername, filename)
file_paths.append(file_path)
# 打印文件路径及文件名,并存储到文件
with open(output_file, 'w') as output:
output.write("Files with name '{}':\n".format(target_filename))
for file_path in file_paths:
print(file_path)
print(file_path, file=output)
# 读取 common_ctrl.v 文件的内容
for file_path in file_paths:
with open(file_path, 'r', encoding='utf-8', errors='ignore') as file:
file_contents[file_path] = file.readlines()
# 比较文件内容并列出不同之处,并存储到文件
for file_path1 in file_paths:
for file_path2 in file_paths:
if file_path1 != file_path2 and (file_path1, file_path2) not in compared_files and (file_path2, file_path1) not in compared_files:
compared_files.add((file_path1, file_path2))
compared_files.add((file_path2, file_path1))
output.write("\nDifferences between '{}' and '{}':\n".format(file_path1, file_path2))
d = difflib.Differ()
diff = list(d.compare(file_contents[file_path1], file_contents[file_path2]))
identical = True
for line_num, line in enumerate(diff, start=1):
if line.startswith('- ') or line.startswith('+ '):
identical = False
output.write("Line {}: {}\n".format(line_num, line.strip()))
print("Line {}: {}".format(line_num, line.strip()))
if identical:
output.write("identical\n")
print("identical")
# 设置根文件夹路径和目标文件名
root_folder = "./"
target_filename = "common_ctrl.v"
output_file = "comparison_result.txt"
# 调用函数进行查找并比较
find_and_compare(root_folder, target_filename, output_file)
例子:
1. common_ctrl.v
module ffn (
input [11:0] gopt_i,
input [11:0] gopt_q,
input [11:0] half_i,
input [11:0] half_q,
output [13:0] helt_i,
output [11:0] helt_q,
output [13:0] hppt_i,
output [11:0] hppt_q
);
assign hppt_i[0] = helt_i[0];
assign hppt_q[0] = helt_q[1];
2 & 3. common_ctrl.v
module ffn (
input [11:0] gopt_i,
input [11:0] gopt_q,
input [11:0] half_i,
input [11:0] half_q,
output [13:0] helt_i,
output [13:0] helt_q,
output [13:0] hppt_i,
output [13:0] hppt_q
);
assign hppt_i[0] = helt_i[0];
assign hppt_q[0] = helt_q[0];
运行python find_and_compare.py 查看结果:
terminal 打印: