我正在寻找一个智能脚本来比较2个文件。我的想法如下:将文件1作为原始文件。文件2是较新的版本,因此将文件1与文件2进行比较并将所有更改添加到文件1.但是:文件2可能包含的条目少于文件1.不应删除文件2中的条目。档案1。 这可以理解吗? ;)
非常感谢您的帮助!
答案 0 :(得分:0)
好吧,如果它真的是python问题,那就有一个difflib库
答案 1 :(得分:0)
查看difflib
This module provides classes and functions for comparing sequences. It can be used for example, for comparing files, and can produce difference information in various formats, including HTML and context and unified diffs. For comparing directories and files.
答案 2 :(得分:0)
正如其他人所说,difflib是要走的路。这是一个例子:
# compare two files
import difflib
d = difflib.Differ()
lines1 = [line for line in file('test1.txt')]
lines2 = [line for line in file('test2.txt')]
results = list(d.compare(lines1,lines2))
newfile_lines = []
for result in results:
operation = result[:2]
line = result[2:]
if operation == '- ': # in first file, not in second
newfile_lines.append(line)
elif operation == ' ': # in both files
newfile_lines.append(line)
elif operation == '+ ': # only in second file
newfile_lines.append(line)
file('test1_with_updates.txt','w').writelines(newfile_lines)