对比两个文件夹中文件文本的差异 python 用文件名为字典的键,文件内容为键对应的值
时间: 2024-04-09 15:28:04 浏览: 66
python-比较两个文件的内容差异,并显示
如果你想将文件名作为字典的键,文件内容作为对应的值,可以对上述代码进行一些修改。下面是修改后的代码:
```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[file] = diff_str
return diffs
# 比较两个文件夹
folder1 = '/path/to/folder1'
folder2 = '/path/to/folder2'
diffs = compare_folders(folder1, folder2)
# 打印差异
for file, diff in diffs.items():
print(f"Diff in file {file}:\n{diff}")
```
在上述代码中,`diffs`变量被修改为一个字典,在每次发现差异时,将文件名作为键,差异信息作为对应的值存入字典中。最后,我们使用`items()`方法遍历字典,并打印出文件名和对应的差异信息。
请替换`/path/to/folder1`和`/path/to/folder2`为实际的文件夹路径。运行代码后,你将得到一个字典,其中键是文件名,值是对应文件的差异信息。
阅读全文