【问题标题】:Comparing contents of txt files in Python在 Python 中比较 txt 文件的内容
【发布时间】:2015-09-26 07:22:52
【问题描述】:

我正在尝试编写一个程序来打开文件、读取内容并将它们与打开的其他文件进行比较。我需要显示它们是否不够相似、相似或彼此的精确副本。我正在尝试使用 filecmp 模块,但它不适合我。到目前为止,这是我所拥有的:

import filecmp

#Opens selected files
file1 = open('file1.txt')
file2 = open('file2.txt')

#Compares different files
filecmp.cmp('file1','file2', shallow=False)

#Closes Files
filecmp.clear_cache()
close.file1
close.file2

有什么建议吗?

【问题讨论】:

  • 不确定 filecmp 但至少致电file1.close()
  • filecmp 只会显示相同的文件,你如何定义“相似”?

标签: python file-comparison


【解决方案1】:

filecmp 使用错误的工具
试试这个:
1.将每个文件的内容加载到列表中
2.将列表变成集合 3.从另一组中减去一组 4. 结果提供了您可以分析的两者之间的差异。

例如:

list1 = set(line.strip() for line in open("file1.txt"))
list2 = set(line.strip() for line in open("file2.txt"))
diff1 = list1 - list2 # subtract 1 set from the other for the difference
diff2 = list2 - list1 # subtract 1 set from the other for the difference
save = open("diff.txt",'w') # Write file differences details for analysis
for i in diff1:
    save.write(i+'\n')
save.close()
save = open("diff2.txt",'w') # Write file differences details for analysis
for i in diff2:
    save.write(i+'\n')
save.close()

或者看difflibhttps://docs.python.org/3.5/library/difflib.html#difflib.Differ

【讨论】:

    【解决方案2】:
    >>> import filecmp
    >>> filecmp.cmp('C://Desktop/a.txt', 'C://Desktop/b.txt')
    True
    >>> 
    

    在这种情况下,我有 2 个文本文件 a.txtb.txt。两个文件都包含相同的一行string

    如果我将其中一个文件中的 string 更改为不同的内容,则输出为 False

    【讨论】: