比较两个文本文件并输出差异+找到记录的文件名

2024-10-03 09:10:01 发布

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

你好,我写了一个脚本,比较两个文本文件,并将差异输出到一个单独的文本文件(difference.txt)。我的目标是在我的difference.txt中移动到下一行之前,在每一行的开头或结尾获取记录的文件名

我的剧本非常简单:

Jan = "JanFile.txt"
Feb = "FebFile.txt"
rootFolder = os.path.dirname(os.path.abspath(__file__))

with open (Jan, "rt") as doc1, open(Feb, "rt") as doc2:
    prevMonth = set(doc1.readlines())
    currentMonth = set(doc2.readlines())

with open ('TxtDiff.txt', 'wt') as unmatchedFile:
    line = (currentMonth - prevMonth)
    unmatchedFile.writelines(line)

重申一下:我想知道difference.txt文件中的记录来自哪个文件。是否还要附加此信息,使其显示在行之前或之后

例如:

JanFile看起来像:

Column1 | Column2
Data1   | Data2

FebFile看起来像:

Column1 | Column2
Data1   | Data2

Difference.txt的格式如下:

Column1 | Column2 | Column3
JanFile | Data1   | Data2
FebFile | Data1   | Data2
FebFile | Data1   | Data2
JanFile | Data1   | Data2

我很坚持使用 line=(currentMonth-prevMonth)因为使用diff、pandas、xlrd等产生了许多其他问题

在此问题上的任何帮助都将不胜感激。 谢谢


Tags: txtas记录lineopen文本文件column1data1