Python使用difflib比较文件,结果不正确

2024-05-04 23:39:27 发布

您现在位置:Python中文网/ 问答频道 /正文

无法获取这两个文件之间的差异。如果内容已排序,则可以提取差异。但是如果文件的内容在2之间不同,则无法获取差异

File A:
name:TEST1
type:localfile
filefull:True
filemonitored:True
fileziehigh:60
Destination:/tmp
flesizehigh:20
FIle B:
name:TEST1
type:localfile
description:
filefull:True
filemaxline:5000
filemonitored:True
fileziehigh:60
filelow:True
flesizehigh:20
monitor:True
folder:Root
folderowner:Root
 with open(FileA, 'r') as read_src:  
    with open(FileB,'r') as read_dst:
       diff = list(d.compare(read_src.read().splitlines(), read_dst.read().splitlines()))
 print(diff)

正在尝试获取差异,但无法检索。 获得任何指导或更好的方式


Tags: 文件nametrue内容readtypewithroot
1条回答
网友
1楼 · 发布于 2024-05-04 23:39:27

对我来说很好:

import difflib

d = difflib.Differ()
with open('FileA', 'r') as read_src:  
    with open('FileB','r') as read_dst:
        diff = list(d.compare(read_src.read().splitlines(), read_dst.read().splitlines()))

print('\n'.join(diff))

哪张照片

  name:TEST1
  type:localfile
+ description:
  filefull:True
+ filemaxline:5000
  filemonitored:True
  fileziehigh:60
- Destination:/tmp
+ filelow:True
  flesizehigh:20
+ monitor:True
+ folder:Root
+ folderowner:Root

编辑:这是两个文件的正确Myers差异。这不是您想要的输出吗

相关问题 更多 >