使用 context_diff 只打印有差异的行
Using context_diff print only lines which have differences
我有下面的代码打印两个文件之间的差异,我使用了 difflib 模块中的 context_diff。
import difflib
file1 = open(“filename1.json”,”r”)
file2 = open(“filename2.json”,”r”)
diff = difflib.context_diff(file1.readLines(), file2.readLines())
delta = ‘’.join(diff)
print(delta)
filename1.json
{
“Name” : “John”,
“Occupation” : “Manager”,
“Age” : 35,
“Company” : “vTech”
}
filename2.json
{
“Name” : “Mel”,
“Occupation” : “Developer”,
“Age” : 35,
“Company” : “vTech”
}
我只想打印有差异的行。无论如何我们可以做到吗?如果是这样请建议。谢谢我提前了。
预期输出:
! “姓名”:“约翰”,
! “职业”:“经理”,
! “姓名”:“梅尔”,
! “职业”:“开发人员”,
实际产量
! “姓名”:“约翰”,
! “职业”:“经理”,
“年龄”:35,
“公司”:“伟易达”
! “姓名”:“梅尔”,
! “职业”:“开发人员”,
“年龄”:35,
“公司”:“伟易达”
来自the docs:
difflib.context_diff(a, b, fromfile='', tofile='', fromfiledate='', tofiledate='', n=3, lineterm='\n')
Context diffs are a compact way of showing just the lines that have changed plus a few lines of context. The changes are shown in a before/after style. The number of context lines is set by n which defaults to three.
尝试将 n
设置为 0
以不显示上下文:
diff = difflib.context_diff(file1.readLines(), file2.readLines(), n=0)
我有下面的代码打印两个文件之间的差异,我使用了 difflib 模块中的 context_diff。
import difflib
file1 = open(“filename1.json”,”r”)
file2 = open(“filename2.json”,”r”)
diff = difflib.context_diff(file1.readLines(), file2.readLines())
delta = ‘’.join(diff)
print(delta)
filename1.json
{
“Name” : “John”,
“Occupation” : “Manager”,
“Age” : 35,
“Company” : “vTech”
}
filename2.json
{
“Name” : “Mel”,
“Occupation” : “Developer”,
“Age” : 35,
“Company” : “vTech”
}
我只想打印有差异的行。无论如何我们可以做到吗?如果是这样请建议。谢谢我提前了。
预期输出:
! “姓名”:“约翰”,
! “职业”:“经理”,
! “姓名”:“梅尔”,
! “职业”:“开发人员”,
实际产量
! “姓名”:“约翰”,
! “职业”:“经理”,
“年龄”:35,
“公司”:“伟易达”
! “姓名”:“梅尔”,
! “职业”:“开发人员”,
“年龄”:35,
“公司”:“伟易达”
来自the docs:
difflib.context_diff(a, b, fromfile='', tofile='', fromfiledate='', tofiledate='', n=3, lineterm='\n')
Context diffs are a compact way of showing just the lines that have changed plus a few lines of context. The changes are shown in a before/after style. The number of context lines is set by n which defaults to three.
尝试将 n
设置为 0
以不显示上下文:
diff = difflib.context_diff(file1.readLines(), file2.readLines(), n=0)