对比两个文件夹中文件文本的差异 python
时间: 2023-09-08 22:07:48 浏览: 88
要对比两个文件夹中文件文本的差异,可以使用Python的difflib模块。difflib模块提供了一些函数用于执行文本比较和差异计算。下面是一个简单的示例代码:
```python
import difflib
import os
def compare_folders(folder1, folder2):
# 获取文件列表
files1 = os.listdir(folder1)
files2 = os.listdir(folder2)
# 比较文件内容
diffs = []
for file in files1:
if file in files2:
file1_path = os.path.join(folder1, file)
file2_path = os.path.join(folder2, file)
with open(file1_path, 'r') as file1, open(file2_path, 'r') as file2:
diff = difflib.unified_diff(file1.readlines(), file2.readlines(), lineterm='')
diff_str = '\n'.join(diff)
if diff_str:
diffs.append(f"Diff in file {file}:\n{diff_str}")
return diffs
# 比较两个文件夹
folder1 = '/path/to/folder1'
folder2 = '/path/to/folder2'
diffs = compare_folders(folder1, folder2)
# 打印差异
for diff in diffs:
print(diff)
```
在上面的代码中,`compare_folders`函数接受两个文件夹路径作为参数,然后遍历两个文件夹中的文件,逐个比较文件内容。如果发现差异,就将差异信息添加到`diffs`列表中。最后,我们可以遍历`diffs`列表并打印出所有的差异。
请替换`/path/to/folder1`和`/path/to/folder2`为实际的文件夹路径。运行代码后,你将得到两个文件夹中文件文本的差异信息。
阅读全文