【发布时间】:2014-01-08 07:34:05
【问题描述】:
我有两个包含相同行数的文件。
"file1.txt" contains following lines:
Attitude is a little thing that makes a big difference
The only disability in life is a bad attitude
Abundance is, in large part, an attitude
Smile when it hurts most
"file2.txt" contains:
Attitude is a little thing that makes a big difference
Everyone has his burden. What counts is how you carry it
Abundance is, in large part, an attitude
A positive attitude may not solve all your problems
我想逐行比较两个文件,如果两个文件之间的任何行不匹配,我想
print "mismatch in line no: 2"
print "mismatch in line no: 4" #in this case lineno: 2 and lineno: 4 varies from second file
我试过了。但是我只能打印 file1 中与 file2 中的行不同的行。无法打印不匹配行的行号。??
My code:
with open("file1.txt") as f1:
lineset = set(f1)
with open("file2.txt") as f2:
lineset.difference_update(f2)
for line in lineset:
print line
【问题讨论】:
-
你为什么要把它做成一套?是否要删除重复项?
-
不,我不想删除该行。我想打印与 file2 行不匹配的 file1 的行号。在我的情况下,第 2 行和第 4 行与 file2 不同。所以我想打印不匹配在第 2 行和第 4 行
-
你听说过
diff吗?这有点重新发明轮子..
标签: python python-2.7 file-comparison